2017-09-13 121 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';