Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 505
ACDev Avatar asked Oct 24 '25 04:10

ACDev


1 Answers

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[];
  };
};
like image 148
fortunee Avatar answered Oct 25 '25 17:10

fortunee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!