Home > Blockchain >  How to convert to interface an object without knowing keys?
How to convert to interface an object without knowing keys?

Time:04-23

I want to convert a json into a typescript object. Example of the json:

{
  "key1": {
    "a": "b"
  },
  "key2": {
    "a": "c"
  }
}

The key key1 & key2 are not known. So, I can't just directly put them as interface. The object associated with their key are always the same.

Actually, I made the object like:

export interface MyObj {
  a: string;
}

But how can I do to make the json converted into an object ?

I tried to directly made a map as object type like:

export interface AllMyObj {
  valKey: Map<string, MyObj>;
}

But I don't know what to set instead of valKey.

CodePudding user response:

Your interface should extend Record<string, MyObj> (TS playground):

export interface MyObj {
  a: string;
}

interface AllMyObj extends Record<string, MyObj>{}

Or just use it as a type (TS playground):

export interface MyObj {
  a: string;
}

type AllMyObj = Record<string, MyObj>
  • Related