Anna
Anna

Reputation: 1689

Unable to assign value to key in Object in angular/typescript

I work on angular and I am unable to assign value to the key. My model is like below

export class aa{
    types: bb[];
}

export interface bb{
    name: string;
    age: string;
}

On my ts file, I did:

    newType: bb;

    initValues(){
    this.newType.name = 'Anna'; //error at this line
}

but I am getting an error as cannot get property of undefined.

Where am I going wrong? How can I assign value to a key in angular

Upvotes: 1

Views: 516

Answers (1)

Suren Srapyan
Suren Srapyan

Reputation: 68645

Now you have only declared the type of your newType property. You need also to initialize your property

newType: bb = { name: null, age: null };

Or you can say that the properties are optional and don't explicitly assign them null

export interface bb{
    name?: string;
    age?: string;
}

newType: bb = { };

Upvotes: 1

Related Questions