我正在使用 typescript
在 Angular2 中编写代码。我有这个对象:
export class Car{
name: String;
door: {
position: String;
id: Number;
};
}
我已经按照以下步骤初始化了对象:
constructor() {
this.door= new Door();
}
export class Door{
position: String;
ID: Number
}
而且效果很好。当我尝试初始化一个对象数组时,我的问题就开始了
export class Car{
name: String;
door: {
position: String;
id: Number;
};
color: {
one: String;
two: String;
}[]
}
我也尝试这样做 已编辑
constructor() {
for (var i = 0; i < 10; i++) {
this.color.push(new Color);
}
this.door= new Door();
}
export class Color{
one: String;
two: String;
}
错误如下:
ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'push' of undefined TypeError: Cannot read property 'push' of undefined
最佳答案
问题是您将 color
属性声明为具有 {one: string; 类型的单个项目的元组。二:字符串
要初始化你可以使用的元组
this.color= [new Color()];
或者如果你想声明一个你可以使用的类型的数组:
color: {
one: String;
two: String;
}[]
并用一个空数组初始化它:
this.color= [];
// Push 10 elements in the array, you can replace 10 with how many elements you need.
for(let i = 0; i< 10; i++) this.color.push(new Color());
有关元组的更多信息 here
关于angular - 对象的构造函数数组 - typescript ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48304952/