带有对象的复杂 Typescript 接口
2018-08-14
2353
我有一个定义为:
export interface Address {
addressType: {
house?: {
streetAddress: string,
city: string,
zip: string,
},
apartment?: {
streetAddress: "",
unitNumber: "",
city: "",
zip: "",
buildingName?: "",
},
}
instructions?: string;
}
然后在我的组件的 Typescript 文件中,我定义了一个房屋地址:
address: Address;
constructor() {
this.address.addressType = {
house: {
streetAddress: "1 test",
city: "test city",
zip: "92222",
}
}
console.log(this.address);
}
但是当我将地址记录到控制台时,我得到的是:
Uncaught (in promise): TypeError: Cannot set property 'addressType' of undefined
我以为我在构造函数中设置了 addressType。有没有更有效的方法来完成我正在做的事情?
3个回答
您需要初始化
this.address
才能设置其 addressType:
constructor() {
this.address = {
addressType: {
house: {
streetAddress: "1 test",
city: "test city",
zip: "92222",
}
}
};
console.log(this.address);
}
jh314
2018-08-14
首先初始化您的
address
以引用一个对象。这将为您的对象提供内存,然后您可以初始化嵌套属性。
address: Address = { addressType: {} };
constructor() {
this.address.addressType = {
house: {
streetAddress: "1 test",
city: "test city",
zip: "92222",
}
}
console.log(this.address);
}
Suren Srapyan
2018-08-14
您必须初始化
address
属性,因为注释任何具有类型的属性都不会提供值,并且它的初始值为
undefined
。
您可以像这样初始化您的属性
address: Address = { addressType: {} };
但我认为这里最好的方法是创建一个基于地址接口的类
export interface IAddress {
addressType: {
house?: {
streetAddress: string,
city: string,
zip: string,
},
apartment?: {
streetAddress: "",
unitNumber: "",
city: "",
zip: "",
buildingName?: "",
},
}
instructions?: string;
}
class Address implements IAddress {
addressType: { house?: { streetAddress: string; city: string; zip: string; };
apartment?: { streetAddress: ""; unitNumber: ""; city: ""; zip: ""; buildingName?: ""; }; };
instructions?: string;
constructor() {
this.addressType = {};
}
}
您可以像这样使用它
address: Address = new Address();
house property of addressType is
undefined
// this will throw an error can't read streetAddress of undefined
{{address.addressType.house.streetAddress}}
为了解决上述错误,您可以像
addressType
一样初始化
constructor() {
this.addressType = {};
this.addressType.house = {}
}
house
Muhammed Albarmavi
2018-08-14