1

I need some help defining a type for a JSON file with the following format,

{
  "UID_ABC1" : {
      "name": "test",
      "email": "test@whatever.com"
  },
  "UID_DEF2" : {
      "name": "test2",
      "email": "test2@whatever.com"
  },
  ...,
  "UID_XYZ3" : {
      "name" : "test 7",
      "email": "test7@whatever.com"
  },
  "globalConfig" : {
      "isEnabled": true
  }
}

There are an unknown number of UID key/value pairs but there is always just one globalConfig object. I cannot change the format of the JSON. The UIDs are basically just randomly generated strings that I do not know ahead of time and the inner objects are just made up of standard fields that are trivial to type, so I am mainly concerned with the top level typing.

Something like this is close,

export interface MyJsonType {
  [key: string]: MyType,
  globalConfig: MyConfigType
}

But does not account for the multiple types. There is a syntax error complaining about MyConfigType.

David Kidwell
  • 600
  • 1
  • 6
  • 15
  • 1
    Are the UIDs completely random or do they start with `"UID_"` as shown in your example? If they have a common prefix you can handle it with a pattern template literal index signature as shown [here](https://tsplay.dev/mLq82W). – jcalz Jun 21 '22 at 19:54
  • Completely random, unfortunately – David Kidwell Jun 21 '22 at 19:59
  • 1
    When you say `{ [key: string]: MyType, globalConfig: MyConfigType }` doesn't account for multiple UID entries, can you elaborate? Index signatures account for any number of entries. The problem I'd imagine with that type is that it's not a valid TypeScript type unless `MyConfigType` happens to be a subtype of `MyType`, which it isn't in your example. – jcalz Jun 21 '22 at 19:59
  • 1
    If they're completely random then this is essentially a duplicate of [this question](https://stackoverflow.com/q/61431397/2887218); your type is a dictionary of `MyType` with a single `globalConfig` property of type `MyConfigType`. There is currently no way in TypeScript to represent that as a specific type – jcalz Jun 21 '22 at 20:00
  • 1
    Ah good find, that answers my question. Thank you for the help, I appreciate it. Sounds like I am forced to do something like [key: string]: MyType | MyConfigType – David Kidwell Jun 21 '22 at 20:04

0 Answers0