我想要定义与对象和不同类型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
是否有错的问题? –