Home > front end >  Define typescript interface for generalized json
Define typescript interface for generalized json

Time:04-01

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 ?

CodePudding user response:

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;
}
  • Related