简体   繁体   English

无法为角度/打字稿中的对象中的键分配值

[英]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: 在我的ts文件中,我做了:

    newType: bb;

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

but I am getting an error as cannot get property of undefined . 但我收到一个错误,因为cannot get property of undefined

Where am I going wrong? 我要去哪里错了? How can I assign value to a key in angular 如何为angular中的键分配值

Now you have only declared the type of your newType property. 现在,您只声明了newType属性的类型。 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 或者您可以说这些属性是可选的,并且不将它们显式分配为null

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

newType: bb = { };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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