I have some code:
enum Color {
Red,
Green,
Blue
}
function getColorName(c: Color): string {
switch(c) {
case Color.Red:
typescript-eslint has "exhaustiveness checking in switch with union type" rule:
@typescript-eslint/switch-exhaustiveness-check
To avoid Typescript or linter warnings:
default:
((_: never): void => {})(c);
in context:
function getColorName(c: Color): string {
switch(c) {
case Color.Red:
return 'red';
case Color.Green:
return 'green';
default:
((_: never): void => {})(c);
}
}
The difference between this solution and the others is
never execute anywayYou don't need to use never or add anything to the end of your switch.
If
switch statement returns in each casestrictNullChecks typescript compilation flag turned onundefined or voidYou will get an error if your switch statement is non-exhaustive as there will be a case where nothing is returned.
From your example, if you do
function getColorName(c: Color): string {
switch(c) {
case Color.Red:
return 'red';
case Color.Green:
return 'green';
// Forgot about Blue
}
}
You will get the following compilation error:
Function lacks ending return statement and return type does not include
undefined.
As a nice twist on Ryan's answer, you can replace never with an arbitrary string to make the error message more user friendly.
function assertUnreachable(x: 'error: Did you forget to handle this type?'): never {
throw new Error("Didn't expect to get here");
}
Now, you get:
return assertUnreachable(c);
~~~~~~~~~~~~~~~~~~~~~
Type "Color.Blue" is not assignable to type "error: Did you forget to handle this type?"
This works because never can be assigned to anything, including an arbitrary string.