I'm trying to use the following pattern:
enum Option {
ONE = 'one',
TWO = 'two',
THREE = 'three'
}
interface OptionRequirement {
someBool: boolean;
someString: string;
}
interface OptionRequirements {
[key: Option]: OptionRequirement;
}
This seems very straightforward to me, however I get the following error:
An index signature parameter type cannot be a union type. Consider using a mapped object type instead.
What am I doing wrong?
You can use TS "in" operator and do this:
enum Options {
ONE = 'one',
TWO = 'two',
THREE = 'three',
}
interface OptionRequirement {
someBool: boolean;
someString: string;
}
type OptionRequirements = {
[key in Options]: OptionRequirement; // Note that "key in".
}
The simplest solution is to use Record
type OptionRequirements = Record<Options, OptionRequirement>
You can also implement it yourself as:
type OptionRequirements = {
[key in Options]: OptionRequirement;
}
This construct is only available to type, but not interface.
The problem in your definition is saying the key of your interface should be of type Options, where Options is an enum, not a string, number, or symbol.
The key in Options means "for those specific keys that's in the union type Options".
type alias is more flexible and powerful than interface.
If your type does not need to be used in class, choose type over interface.
In my case:
export type PossibleKeysType =
| 'userAgreement'
| 'privacy'
| 'people';
interface ProviderProps {
children: React.ReactNode;
items: {
// ↙ this colon was issue
[key: PossibleKeysType]: Array<SectionItemsType>;
};
}
I fixed it by using in operator instead of using :
~~~
interface ProviderProps {
children: React.ReactNode;
items: {
// ↙ use "in" operator
[key in PossibleKeysType]: Array<SectionItemsType>;
};
}