2017-09-13 39 views
0

我想要定義與對象和不同類型A接口 如,我們怎樣才能打字稿定義對象類型的接口?

export interface example { 
    code: string; 
    category : { 
    name : string, 
    reference: string, 
    sequence : number 
    }; 
} 

在定義中,是沒有問題的,但調用等之後

ex = {} as example; 
ex.category.name ='electric; 

這並不工作,下面的錯誤發生

ERROR Error: Uncaught (in promise): TypeError: Cannot set property 'name' of undefined TypeError: Cannot set property 'name' of undefined

有一些相似的主題,但它們並不完全相關。 (How to define object in type script interfaceHow can I define the types of an object variable in Typescript?

我感謝您的幫助尋找解決方案。

+0

你仍然需要創建的第一個級別對象:'ex.category = {};',或者只是去直接到'讓前= {category:{name:'electric'}};'。接口只是描述了*形狀*,你還是要建立正確的對象(或寫一類構造函數,或提供默認值)。 – jonrsharpe

+0

是否有錯的問題? –

回答

0

Type assertions並不意味着該對象一定會是你在運行時斷言形狀。可以斷言任何對象是任何類型的,但最終會在運行時失敗,如果你的運行時類型不匹配。

在您的例子中,ex對象不具有category屬性,因此它會undefined在運行時這會導致你的錯誤。

你可以在你的對象初始化category屬性,以及:

var ex = { 
    category: {} // or you can initialize `name` here as well 
} as example; 
ex.category.name = 'electric';