简体   繁体   中英

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

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 = { };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM