Let's say you have a switch
statement that handles all values of an enum (or some other type with a limited number of possible values). When you extend that enum sometime in the future you may forget to add a new case to the statement.
With TypeScript you can use an assertUnreachable()
function to ensure that all possible cases are handled:
function myFunction(value: SomeEnum) {
switch (value) {
case SomeEnum.ONE:
// ...
break;
case SomeEnum.TWO:
// ...
break;
default:
// Ensures that all cases are handled
assertUnreachable(value);
}
}
The assertUnreachable()
function works by defining an argument of type never
:
function assertUnreachable(_value: never): never {
throw new Error("Statement should be unreachable");
}
When you now extend the enum TypeScript will show an error: