[英]Typescript: How do I define interfaces for nested objects array
假设我有一个 JSON 有效载荷解析成这样的东西
{
"status": "123",
"totalResults": 1234,
"articles": [
{
"source": {
"id": "123",
"name": "123"
},
"author": "123",
"title": "123",
"url": "123",
"imgUrl": "123",
"publishedAt": "123",
"content": "123"
},
]
}
我如何将 Example 接口的定义设置为 model,即 items 属性的值为 object,其键为字符串,其值由 Item 接口定义:
interface Item {
status: string;
totalResults: number;
id: string
name: string
author: string
title: string
description: string
url: string
urlToImage: string
publishedAt: string
content: string
}
interface Example extends Item{
articles: Array<Object>;
source: {
[key: string]: Item
};
}
const example: Example = {
"status": "123",
"totalResults": 1,
"articles": [
{
"source": {
"id": "123",
"name": "123"
},
"author": "123",
"title": '123',
"description": "123",
"url": "123",
"urlToImage": "123",
"publishedAt": "123",
"content": "123"
},
]
}
这是一个正确键入的版本,但我不确定这是否是您正在寻找的。
interface Item {
status: string;
totalResults: number;
articles: Array<Articles>;
}
interface Articles {
source: Source // or source: { id: string; name: string };
author: string;
title: string;
description: string;
url: string;
urlToImage: string;
publishedAt: string;
content: string;
}
interface Source {
id: string;
name: string;
}
const example: Item = {
"status": "123",
"totalResults": 1,
"articles": [
{
"source": {
"id": "123",
"name": "123"
},
"author": "123",
"title": '123',
"description": "123",
"url": "123",
"urlToImage": "123",
"publishedAt": "123",
"content": "123"
},
]
}
export interface Reference{
status:string,
totalResults: number,
articles:
{
source: {
id: string,
name: string
},
author: string,
title: string,
url: string,
imgUrl: string,
publishedAt: string,
content: string
}[]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.