Consider the following code:
enum MyEnum {
Enum1,
Enum2
}
function switchOverEnum(myEnum: MyEnum) {
switch (myEnum) {
case MyEnum.Enum1:
console.log('it is an enum1');
break;
// I am missing the case MyEnum.Enum2 here,
// but the TypeScript compiler does not complain
}
}
I am using this in a project created using create-react-app. My expectation is that TypeScript complains that the case MyEnum.Enum2 is not handled, but it doesn't. How can I confiugre the TypeScript compiler to do so?
Do it this way
enum MyEnum {
Enum1,
Enum2
}
function switchOverEnum(myEnum: MyEnum) {
switch (myEnum) {
case MyEnum.Enum1:
console.log('it is an enum1');
break;
case MyEnum.Enum2:
console.log('it is an enum2');
break;
default:
const exhaustiveCheck: never = myEnum;
throw new Error(`Unhandled Enum case: ${exhaustiveCheck}`);
}
}
Or with the anonymous function
default:
((x: never) => {
throw new Error(`${x} was unhandled!`);
})(c);
see here playground
For more ways see here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With