angular - 无法在角度/打字稿中为对象中的键赋值
问题描述
我在角度工作,我无法为键赋值。我的模型如下
export class aa{
types: bb[];
}
export interface bb{
name: string;
age: string;
}
在我的 ts 文件中,我做了:
newType: bb;
initValues(){
this.newType.name = 'Anna'; //error at this line
}
但我收到一个错误,因为cannot get property of undefined
.
我哪里错了?如何为角度中的键赋值
解决方案
现在你只声明了你的newType
属性的类型。您还需要初始化您的属性
newType: bb = { name: null, age: null };
或者您可以说这些属性是可选的并且不明确分配它们null
export interface bb{
name?: string;
age?: string;
}
newType: bb = { };