switch-exhaustiveness-check
Require switch-case statements to be exhaustive with union type.
Some problems reported by this rule are manually fixable by editor suggestions.
This rule requires type information to run.
When working with union types in TypeScript, it's common to want to write a switch
statement intended to contain a case
for each constituent (possible type in the union).
However, if the union type changes, it's easy to forget to modify the cases to account for any new types.
This rule reports when a switch
statement over a value typed as a union of literals is missing a case for any of those literal types and does not have a default
clause.
module.exports = {
"rules": {
"@typescript-eslint/switch-exhaustiveness-check": "warn"
}
};
Examples
- ❌ Incorrect
- ✅ Correct
- ✅ Correct
type Day =
| 'Monday'
| 'Tuesday'
| 'Wednesday'
| 'Thursday'
| 'Friday'
| 'Saturday'
| 'Sunday';
const day = 'Monday' as Day;
let result = 0;
switch (day) {
case 'Monday':
result = 1;
break;
}
type Day =
| 'Monday'
| 'Tuesday'
| 'Wednesday'
| 'Thursday'
| 'Friday'
| 'Saturday'
| 'Sunday';
const day = 'Monday' as Day;
let result = 0;
switch (day) {
case 'Monday':
result = 1;
break;
case 'Tuesday':
result = 2;
break;
case 'Wednesday':
result = 3;
break;
case 'Thursday':
result = 4;
break;
case 'Friday':
result = 5;
break;
case 'Saturday':
result = 6;
break;
case 'Sunday':
result = 7;
break;
}
type Day =
| 'Monday'
| 'Tuesday'
| 'Wednesday'
| 'Thursday'
| 'Friday'
| 'Saturday'
| 'Sunday';
const day = 'Monday' as Day;
let result = 0;
switch (day) {
case 'Monday':
result = 1;
break;
default:
result = 42;
}
Options
This rule is not configurable.
When Not To Use It
If you don't frequently switch
over union types with many parts, or intentionally wish to leave out some parts.