简体   繁体   English

我们如何在打字稿中定义对象类型接口?

[英]How can we define object type interface in typescript?

I want to define a interface with object and different types such as 我想用对象和不同类型定义接口,例如

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

In definition, there is no problem but after calling like 在定义上,没有问题,但是在调用

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

this does not work and below error occurs 这不起作用,并且发生以下错误

ERROR Error: Uncaught (in promise): TypeError: Cannot set property 'name' of undefined TypeError: Cannot set property 'name' of undefined 错误错误:未捕获(承诺):TypeError:无法设置未定义的属性“名称” TypeError:无法设置未定义的属性“名称”

There are some similar subjects but they are not exactly related. 有一些相似的主题,但它们并不完全相关。 ( How to define object in type script interface or How can I define the types of an object variable in Typescript? ) 如何在类型脚本界面中定义对象,或者如何在Typescript中定义对象变量的类型?

I appreciate your assistance finding the solution. 感谢您协助我们找到解决方案。

Type assertions do not mean the object will definitely be of the shape you are asserting at runtime. 类型断言并不意味着对象肯定具有您在运行时断言的形状。 You can assert any object is of any type, but ultimately it will fail at runtime if your runtime type does not match. 您可以断言任何类型的对象,但是如果您的运行时类型不匹配,最终它将在运行时失败。

In your example, the ex object does not have a category property so it will be undefined at runtime which leads to your error. 在您的示例中, ex对象没有category属性,因此它将在运行时undefined ,这会导致您出错。

You can initialize the category property as well in your object: 您也可以在对象中初始化category属性:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM