[英]Define typescript interface for generalized json
我有以下 json,其中 carModels 包含以下格式。 如何定义接口?
{
"name": "name",
"version": 1.0,
"cars": [{
"id": 1,
"carModelID": "1"
}],
"carModels": {
"1": {
"id": 1,
"name": "Tesla"
},
"2": {
"id": 2,
"name": "Benz"
}
}
}
我使用在线生成器来获得以下界面。 如何概括以下接口,以便 CarModel 接口可以将任何值作为键?
export interface Root {
name: string
version: number
cars: Car[]
carModels: CarModels
}
export interface Car {
id: number
carModelID: string
}
export interface CarModels {
"1": N1
"2": N2
}
export interface N1 {
id: number
name: string
}
export interface N2 {
id: number
name: string
}
上面的CarModels
定义了N1
和N2
....如何将 CarModels 接口推广到任何类型?
您将为CarModel
编写一个接口,然后为包含的结构使用索引类型:
interface CarModel {
id: number;
name: string;
}
interface CarModels {
[key: string]: CarModel;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.