Sometimes, we want to fix TypeScript enum switch statement not working.
In this article, we’ll look at how to fix TypeScript enum switch statement not working.
How to fix TypeScript enum switch statement not working?
To fix TypeScript enum switch statement not working, we should make sure we’re comparing numbers with switch
if we didn’t assign any value non-number to the enum values.
For instance, we write
enum EditMode {
View = 0,
Edit = 1,
Delete = 2,
}
switch (+editMode) {
case EditMode.Delete:
//...
break;
case EditMode.Edit:
// ...
break;
default:
//...
break;
}
to create the EditMode
enum that has numbers assigned to each entry.
Then we make sure editMode
is a number before doing comparisons by adding a +
sign in front of it.
Then the switch
statement should do the comparisons property since we’re comparing 2 numbers.
Conclusion
To fix TypeScript enum switch statement not working, we should make sure we’re comparing numbers with switch
if we didn’t assign any value non-number to the enum values.