Skip to main content

switch-exhaustiveness-check

Require switch-case statements to be exhaustive with union types and enums.

💡

Some problems reported by this rule are manually fixable by editor suggestions.

💭

This rule requires type information to run.

When working with union types or enums 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 or the enum). However, if the union type or the enum 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 or as an enum is missing a case for any of those literal types and does not have a default clause.

.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/switch-exhaustiveness-check": "error"
}
};
Try this rule in the playground ↗

Examples

When the switch doesn't have exhaustive cases, either filling them all out or adding a default will correct the rule's complaint.

Here are some examples of code working with a union of literals:

type Day =
| 'Monday'
| 'Tuesday'
| 'Wednesday'
| 'Thursday'
| 'Friday'
| 'Saturday'
| 'Sunday';

declare const day: Day;
let result = 0;

switch (day) {
case 'Monday':
result = 1;
break;
}
Open in Playground

Likewise, here are some examples of code working with an enum:

enum Fruit {
Apple,
Banana,
Cherry,
}

declare const fruit: Fruit;

switch (fruit) {
case Fruit.Apple:
console.log('an apple');
break;
}
Open in Playground

Options

This rule is not configurable.

When Not To Use It

If you don't frequently switch over union types or enums with many parts, or intentionally wish to leave out some parts.

Resources