Home > OS >  Getting error every time after assign interface to Object - Typescript
Getting error every time after assign interface to Object - Typescript

Time:08-04

Getting error after assigning an interface to any object in typescript.

I have two below interface.

export interface UserInfo {
    firstName: string,
    lastName: string,
    lastUpdateTime: string,
    status: string
}

export interface User{
    activeCount: string,
    subsource: string,
    users: UserInfo[]
}

After assign the above User interface to an object in a component getting error.

user: User= {}; // Type {} is missing the properties 
user: User;

CodePudding user response:

Its because when you specify a property of the type like this firstName: string the property should be present (its required) please change its definition to firstName?: string, which means the property is an optional property and can be not defined!

Then the error will go away!

export interface UserInfo {
    firstName?: string,
    lastName?: string,
    lastUpdateTime?: string,
    status?: string
}

export interface User{
    activeCount?: string,
    subsource?: string,
    users?: UserInfo[]
}

After assign the above User interface to an object in a component getting error.

user: User= {}; // Type {} is missing the properties - wont come now! 
user: User;

CodePudding user response:

Of course, you need to add the properties to the object:

const user: User = {
  users: [],
  activeCount: "",
  subsource: "",
};

CodePudding user response:

I think you have to tell the compiler that {} is a type of User and contains the same properties as the User interface. For example:

user:User = {} as User;

CodePudding user response:

as per typescript, You Define user: User it set value of user as User to use interface you have to define like : let user: User

CodePudding user response:

You can make properties optional dynamically by mapping them which would be a more generic solution. Disadvantage: You'd lose your interface and had to use a type instead because mapping an interface is not (yet) possible.

interface UserInfo {
    firstName: string;
    lastName: string;
    lastUpdateTime: string;
    status: string;
}

interface User {
    activeCount: string;
    subsource: string;
    users: UserInfo[];
}

export type MakeOptional<T> = { [K in keyof T]?: T[K] };

const user: MakeOptional<User> = {}; // works
  • Related