我想要定義與對象和不同類型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 interface或How can I define the types of an object variable in Typescript?)
我感謝您的幫助尋找解決方案。
你仍然需要創建的第一個級別對象:'ex.category = {};',或者只是去直接到'讓前= {category:{name:'electric'}};'。接口只是描述了*形狀*,你還是要建立正確的對象(或寫一類構造函數,或提供默認值)。 – jonrsharpe
是否有錯的問題? –