Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: Defining an interface with both dynamic and static keys

Im working with data that looks like

{
 8533864186048: "4",
 8533864218816: "1",
 isExchange: true,
 returnType: "exchange",
}

where the first two keys are dynamic but will always be strings

so I tried to define the interface as such:

interface ReturnData {
  [key: string]: string; <- Applying this to whole interface for some reason
  isExchange?: boolean;
  returnType?: ReturnType;
  selectedVariant: Variant;
}

So am having the issue where trying to define a dynamic member on the interface causes ts to try and assign all the other members to type string

What would be the correct way to go about this?

like image 414
Zenith Avatar asked Oct 21 '25 04:10

Zenith


1 Answers

You could do something like:

interface ReturnData {
  isExchange?: boolean;
  returnType?: ReturnType;
  selectedVariant: Variant;
  [key: string]: string | boolean | ReturnType | Variant;
}

But instead of mixing dynamic and static property together, I think you should refactor your interface like this:

interface ReturnData {
  isExchange?: boolean;
  returnType?: ReturnType;
  selectedVariant: Variant;
  someProps: {
    [key: string]: string;
  }
}

so the interface is more readable.

like image 68
hnb Avatar answered Oct 23 '25 20:10

hnb



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!