1

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.

Elikill58
  • 4,050
  • 24
  • 23
  • 45
  • `Record` or `{ [key: string]: MyObj }` ? – VLAZ Apr 22 '22 at 21:32
  • @VLAZ Maybe, I don't know what are they, and which one is better than the other – Elikill58 Apr 22 '22 at 21:38
  • [Enforcing the type of the indexed members of a Typescript object?](https://stackoverflow.com/q/13315131) | [typescript type for object with unknown keys, but only numeric values?](https://stackoverflow.com/q/47847561) | [How to declare a typed object with arbitrary keys?](https://stackoverflow.com/q/36590284) | [What type to use for a dictionary-like object in TypeScript?](https://stackoverflow.com/q/57336063) – VLAZ Apr 22 '22 at 21:44
  • The first and second question seems off-topic according to my own. The last can be a duplicate, but with an answer that doesn't seems so good. Also, I didn't know what to search before posting, so I didn't found good post – Elikill58 Apr 22 '22 at 21:47

1 Answers1

3

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>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • 1
    Generics save the world – Jackkobec Apr 22 '22 at 21:34
  • Why should the interface extend it? To me it makes more sense to just be `type AllMyObj = Record`. Or not even giving it a name at all and using `Record` directly. – VLAZ Apr 22 '22 at 22:10
  • I've the question to literally (he wanted an interface). Using it as a type (with or without naming) is fine as well. Updated the answer. – Ori Drori Apr 22 '22 at 22:17