Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typed and dynamic typed TypeScript interface [duplicate]

Tags:

typescript

i have a question about Typescript interfaces. I've got the following interface:

interface MappingConfiguration {
  [key: string]: Configuration;
  required: string[];
}

interface Configuration {
 a: string;
 b: string;
}

I understand why this doesn't work. The MappingConfiguration interface allows dynamic keys of type Configuration. So any property can be binded on the object. This works as intended. But here's the problem: I also have a property "required", which is a string[]. Typescript does not allow the string[], because it expects the Configuration type. I understand that. So i came up with the following result:

interface MappingConfiguration {
  [key: string]: Configuration | string[];
  required: string[];
}

interface Configuration {
 a: string;
 b: string;
}

This feels totally wrong. Is there maybe another way of combining dynamic and static object keys in an interface? Thanks in advance! :)

like image 255
mactive Avatar asked Feb 27 '26 10:02

mactive


1 Answers

A first quick idea is to add an additional property to MappingConfiguration:

interface MappingConfiguration {
  required: string[];
  configurations?: Record<string, Configuration>;
}
like image 191
pzaenger Avatar answered Mar 01 '26 12:03

pzaenger



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!