One interesting feature of TypeScript is the ability to exhaustively check Enums, such as in switch statements.
Challenge
I am faced with the task of using an Enum as a Generic type to restrict other parameters based on the provided enumVal
.
While it may be simpler to overload the function for this basic example, practicality becomes an issue when dealing with numerous possible combinations. For instance, consider the following enum:
Illustration
enum MyEnum {
FOO = 'foo',
BAR = 'bar'
}
Utilizing the Enum directly results in successful compilation:
function exhaustiveSwitch(enumVal: MyEnum) {
switch (enumVal) {
case MyEnum.FOO:
break
case MyEnum.BAR:
break
default:
const _exhaustiveCheck: never = enumVal
}
}
However, incorporating the Enum as a Generic triggers the error message
Type 'EnumVal' is not assignable to type 'never'
:
function exhaustiveSwitchGeneric<EnumVal extends MyEnum> (enumVal: EnumVal) {
switch (enumVal) {
case MyEnum.FOO:
break
case MyEnum.BAR:
break
default:
const _exhaustiveCheck: never = enumVal //Type 'EnumVal' is not assignable to type 'never'
}
}
(view example here)
Inquiry
- Why does using the Enum as a Generic fail in this scenario?
- Is there an alternative method to utilize the exact value provided (e.g.
MyEnum.FOO
) for another parameter without employing Generics? (excluding function overloading)
While there might be valid reasons behind this behavior, I believe that employing Generics in this manner should yield similar results to direct usage.