Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert to interface an object without knowing keys?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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

export interface MyObj {
  a: string;
}

interface AllMyObj extends Record<string, MyObj>{}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading