2017-09-11 298 views
0

類型的工作,我想聲明的是具有以下結構在打字稿

public car = { 
    price: 20000, 
    currency: EUR, 
    seller: null, 
    model: { 
     color: null, 
     type: null, 
     year: null 
    } as Array<object> 
}; 

然後,當我與此對象工作的對象,我有一些像

public addProduct(typeId: number): void { 
    this.car.model.push({type: typeId}); 
} 

這個問題我我面對的是當我定義model對象,因爲使用as Array<object>產生的東西單獨行

Type '{ color: null; type: null; year: null; }' cannot be converted to type 'object[]'. Property 'length' is missing in type '{ color: null; type: null; year: null; } 

我找不到合適的原因來定義這個。使用push生成一個「空」對象是非常重要的,我可以從該視圖添加屬性。

回答

1

您可以像

let car: any = { 
    price: 20000, 
    currency: 'EUR', 
    seller: null, 
    model: [ 
    { color: 'red', type: 'one', year: '2000' }, 
    { color: 'blue', type: 'two', year: '2001' } 
    ] 
} 

創建打字稿一個對象,然後你可以做你想要的東西

car.model.push({ color: 'green', type: 'three', year: '2002' }); 

添加一個新的模式,或者去取

car.model[0] // returns { color: 'red', type: 'one', year: '2000' } 

另一種選擇是創建一個類而不是一個對象

export class Car { 
    public price: number; 
    public currency: string; 
    public seller: string; 
    public models: any[]; 

    constructor() { } 
} 

然後把所有適當的方法放在類中。

+0

在你的第一個案例中,爲什麼我不能只用其中一個值來執行'push',其餘的被設置爲'null'或任何默認值。正如'car.model.push({year:'2002'});'? – Erythros

+0

no1表示你不能,只需要'model:[]'如果你想要一個空數組並在稍後推入,那麼我只是把一些東西放在這個例子中,或者如果你想要空值,你可以初始化它與所有空值無關 'model:[{color:null,type:null,year:null}]'也可以,但我不明白爲什麼你會希望空值,如果你可以使它成爲一個空的數組 –