如何在Typescript中将对象分配给数组

时间:2019-04-14 23:22:00

标签: typescript

我在Typescript中有一个类,并且在此中分配有问题。课堂的一部分。我收到以下错误。 类型“ ListingHistory”缺少类型“ ListingHistory []”中的以下属性:长度,弹出,推入,连续和另外26个。ts(2740)

下面是我本节的课

export class History {
    public address: string;
    public listingHistory: ListingHistory[];
    public saleHistory: SaleHistory[] ;
    public mortgageHistory: MortgageHistory[];

    constructor(address: string, listingHistory?: ListingHistory, saleHistory ?: SaleHistory ,
                mortgageHistory?: MortgageHistory) {

       this.address = address;
       this.listingHistory = listingHistory;
       this.saleHistory(push)saleHistory;
       this.mortgageHistory = mortgageHistory;

} 

2 个答案:

答案 0 :(得分:1)

您正在将可为空的listingHistory传递给构造函数 您可能需要初始化listingHistory字段

export class History {
public address: string;
public listingHistory: ListingHistory[];
public saleHistory: SaleHistory[];
public mortgageHistory: MortgageHistory[];

constructor(address: string, listingHistory?: ListingHistory, saleHistory ?: SaleHistory ,
            mortgageHistory?: MortgageHistory[]) {

   this.address = address;
   this.listingHistory = listingHistory || [];
   this.saleHistory = saleHistory || [];
   this.mortgageHistory = mortgageHistory || [];

} 

答案 1 :(得分:0)

您创建了一个ListingHistory数组,但将一个ListingHistory项传递给了构造函数

export class History {
public address: string;
public listingHistory: ListingHistory[];
public saleHistory: SaleHistory[] ;
public mortgageHistory: MortgageHistory[];

constructor(public address: string, public listingHistory?: ListingHistory[], public saleHistory ?: SaleHistory[],
            public mortgageHistory?: MortgageHistory[]) {

   this.address = address;
   this.listingHistory = listingHistory;
   this.saleHistory(push)saleHistory;
   this.mortgageHistory = mortgageHistory;

 }