ACDev
ACDev

Reputation: 149

Typescript Dynamic keys in Interface

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.

Upvotes: 4

Views: 8671

Answers (2)

fortunee
fortunee

Reputation: 4332

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[];
  };
};

Upvotes: 4

Shravan Dhar
Shravan Dhar

Reputation: 1560

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

Upvotes: 2

Related Questions