error TS2741: Property is missing in type

Viewed 21429

In file models/User.model.ts (see below) I tried to set a method isEqual as shown in code below. Could someone correct my code ?

file models/User.model.ts:

export class User {
    constructor(
    public firstName: string,
    public lastName: string,
    ) {}

    isEqual (other : User): boolean {
    return other === this;
    }
}

file services/user.service.ts :

import { User } from '../models/User.model';
import { Subject } from 'rxjs/Subject';

export class UserService {

    private users: User[] = [
    {
        firstName: 'William',
        lastName: 'Jones'
    },
    {
        firstName: 'John',
        lastName: 'Doe'
    }
    ];

...

ERROR in services/user.service.ts(7,2): error TS2741: Property 'isEqual' is missing in type '{ firstName: string; lastName: string;}' but required in type 'User'.

4 Answers

ERROR in services/user.service.ts(7,2): error TS2741: Property 'isEqual' is missing in type '{ firstName: string; lastName: string;}' but required in type 'User'.

This is because in your class definition you have the function declared isEqual, but in your list of users you only have the firstName and lastName but not the associated function and the type of users is Users.

{
  firstName: 'William',
  lastName: 'Jones'
},

As mentioned in the comments you could use the new () to make a new User which should also include the function.

public exampleUser = new User("William", "Jones");

This could then in turn be used in an array of Users

public users: Users =  [ this.exampleUser ];

It is specifying that the parameter you are taking in function isEqual should be of type or model as { firstName: 'John', lastName: 'Doe' }, this shows you just need to pass data in this format.

Since support for Partial<T> was added, you can now change the constructor of User to the below, and you should be able to initialize the object by specifying a partial hash of keys and values (as you tried to do above).

constructor(init?:Partial<User>) {
    Object.assign(this, init);
}

From the documentation (currently at https://www.typescriptlang.org/docs/handbook/utility-types.html#partialt):

Constructs a type with all properties of T set to optional. This utility will return a type that represents all subsets of a given type.

Probably you won't prefer this usage, but you can make the method optional, if you do not need isEqual for the items in the array.

Adding question mark(?) to the method name

isEqual?(other: User): boolean

However if you need isEqual for all items, then this solution won't help you as I said in the beginning. By this usage, when you try to use isEqual method it will give undefined error.

Related