简体   繁体   中英

Define typescript interface for generalized json

I have below json, where carModels contains below format. 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?

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?

you'd write an interface for the CarModel then use an index type for the containing structure:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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