为通用 json 定义打字稿接口

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 的接口定义了 N1N2...如何将 CarModels 接口推广到任何类型?

您将为 CarModel 编写接口,然后为包含的结构使用索引类型:

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

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