Skip to main content

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.

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

Examples

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

const day = 'Monday' as Day;
let result = 0;

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

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.

Resources