3

I have an API I'm working with that allows you to search for different games by platform. I'm trying to map out the appropriate interfaces for them, but the top level object key changes with each search type.

The response from the HTTP request gives me back...

ps4: {
  data: [{
    ...
  }]

OR...

xbox: {
  data: [{
    ...
  }]

OR...

switch: {
  data: [{
    ...
  }]

As you can see, the top level object changes with each type of HTTP request, but the data itself remains the same. How do you map out an interface for that key to change dynamically? Thank you.

ACDev
  • 139
  • 3
  • 11
  • Does this answer your question? [How to declare a typed object with arbitrary keys?](https://stackoverflow.com/questions/36590284/how-to-declare-a-typed-object-with-arbitrary-keys) – Heretic Monkey Sep 20 '22 at 18:48

2 Answers2

3

You can define an interface for it like this:

interface Response {
  [key: string]: {
    data: Object[]
  }
}

OR to be more explicit you can define a type with all the possible keys

type TKeys 'ps4' |'xbox' | 'switch';

type Response = {
  [key in TKeys]: {
    data: Object[]
  }
}

You can also consider using an enum type like this

enum Platforms {
 ps4 = 'ps4',
 xbox = 'xbox',
 switch = 'switch'
}

type Response = {
  [key in Platforms]: {
    data: Object[];
  };
};
fortunee
  • 3,852
  • 2
  • 17
  • 29
2

Something like this would work:

interface Data {
    data: object[];
}

interface Response {
    [x: string]: Data
}

Note that I've used object intentionally instead of Object as it suits your case better. More on it here

Shravan Dhar
  • 1,455
  • 10
  • 18