简体   繁体   English

为广义的json定义typescript接口

[英]Define typescript interface for generalized json

I have below json, where carModels contains below format.我有以下 json,其中 carModels 包含以下格式。 How to define the Interface?如何定义接口?

{
    "name": "name",
    "version": 1.0,
    "cars": [{
        "id": 1,
        "carModelID": "1"
    }],
    "carModels": {
        "1": {
            "id": 1,
            "name": "Tesla"
        },
"2": {
            "id": 2,
            "name": "Benz"
        }
    }
}

I used online generator to get the below interface.我使用在线生成器来获得以下界面。 How to generalize below interface so that, CarModel interface can take any value as key?如何概括以下接口,以便 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
}

Problem问题

Above interaface for CarModels defines N1 and N2 ....How do generalize the CarModels interface to any type?上面的CarModels定义了N1N2 ....如何将 CarModels 接口推广到任何类型?

you'd write an interface for the CarModel then use an index type for the containing structure:您将为CarModel编写一个接口,然后为包含的结构使用索引类型:

interface CarModel {
  id: number;
  name: string;
}

interface CarModels {
  [key: string]: CarModel;
}

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

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