Home > Software design >  Typescript Dynamic keys in Interface
Typescript Dynamic keys in Interface

Time:10-17

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.

CodePudding user response:

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

CodePudding user response:

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