I can describe an indexed type restriction in an object type notation such as the following:
enum Enum {
A = 0,
B = 1,
}
type EnumMap = {
[P in Enum]: string;
}
But, surprisingly, the same doesn't seem to be possible when using index notation in an interface:
enum Enum {
A = 0,
B = 1,
}
interface EnumMap {
[P in Enum]: string;
}
The error is:
A computed property name must be of type 'string', 'number', 'symbol', or 'any'.
Is there any reason why this is so? By definition, enums in TypeScript can have only string or number values (or even both, but that's not recommended), and I thought the enum itself would work like a union type for all the values it lists.
Investigating a bit further, I also found that, in the following example, EnumValues
has type number
, instead of (what I expected to be) 0 | 1
. Again, why is this so?
const Enum = {
A: 0,
B: 1
};
type EnumKeys = keyof typeof Enum;
type EnumValues = typeof Enum[EnumKeys];