带对象的复杂打字稿界面

时间:2018-08-14 04:28:06

标签: angular typescript

我的接口定义为:

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 个答案:

答案 0 :(得分:3)

您需要先初始化this.address,然后才能设置其addressType:

constructor() {

    this.address = {
      addressType: {
        house: {
          streetAddress: "1 test",
          city: "test city",
          zip: "92222",
        }
      }
    };        
    console.log(this.address);
}

答案 1 :(得分:3)

首先初始化address以引用一个对象。这将为您的对象提供内存,然后您可以初始化嵌套的属性。

address: Address = { addressType: {} };

constructor() {

    this.address.addressType = {
      house: {
        streetAddress: "1 test",
        city: "test city",
        zip: "92222",
      }
    }        
    console.log(this.address);
}

答案 2 :(得分:2)

您必须初始化address属性,因为注释类型为no的任何属性不提供值,并且它是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();
  

addressType的房屋属性为undefined

// this will throw an error can't read streetAddress of undefined
{{address.addressType.house.streetAddress}}

为了解决以上错误,您可以像house一样初始化addressType

  constructor() {
    this.addressType = {}; 
    this.addressType.house = {}
  }