typescript 打字稿:如何为嵌套对象定义接口?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42216053/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Typescript: How do I define interfaces for nested objects?
提问by bince
Assume I have a JSON payload that parses into something like this:
假设我有一个解析为如下内容的 JSON 有效负载:
{
name: "test",
items: {
"a": {
id: 1,
size: 10
},
"b": {
id: 2,
size: 34
}
}
}
How would I set up the definition of the Example interface to model that the value of the items property is an object whose keys are strings and whose values are defined by the Item interface:
我将如何设置 Example 接口的定义来建模 items 属性的值是一个对象,其键是字符串,其值由 Item 接口定义:
export interface Example {
name: string;
items: ???;
}
export interface Item {
id: number;
size: number;
}
回答by Josh Crozier
Typescript allows you to add a type for the object keys using the syntax [key: string]
.
Typescript 允许您使用语法为对象键添加类型[key: string]
。
As stated in the documentation, these are called indexable types:
如文档中所述,这些称为可索引类型:
Indexable types have an index signature that describes the types we can use to index into the object, along with the corresponding return types when indexing.
可索引类型有一个索引签名,它描述了我们可以用来索引对象的类型,以及索引时相应的返回类型。
In your case, you would use the following:
在您的情况下,您将使用以下内容:
export interface Item {
id: number;
size: number;
}
export interface Example {
name: string;
items: {
[key: string]: Item
};
}
For reference, here is a link to a live example.