switch-exhaustiveness-check
Added in v0.1.4Configuration
Rule Details
Require switch statements over union types to be exhaustive. When switching over a union type (such as a discriminated union or enum), it is easy to forget to handle all possible cases. This rule ensures that every possible value of the union is handled with a case clause, either explicitly or via a default clause, preventing runtime errors from unhandled values.
Examples of incorrect code for this rule:
Examples of correct code for this rule:
Options
allowDefaultCaseForExhaustiveSwitch
If false, a default clause is reported as unnecessary once every member of the union already has its own case.
requireDefaultForNonUnion
If true, also requires a default clause for switches over non-union types (such as number or string), so they are held to the same standard as unions.
considerDefaultExhaustiveForUnions
If true, a default clause on a switch over a union type is itself treated as covering every unhandled member, instead of requiring each member to have an explicit case.
defaultCaseCommentPattern
Regular expression for a trailing comment that stands in for a missing default clause. Defaults to /^no default$/i.
Differences from ESLint
- When a switch is missing more than one case, the order of the types listed in the
missingBranchesmessage and the order the fixer inserts the correspondingcaseclauses follow rslint's internal type ordering rather than the union's declaration order. For example,type Day = 'Monday' | 'Tuesday' | 'Wednesday'reports missing cases as"Monday" | "Tuesday" | "Wednesday", alphabetized, even when the type alias declares them in a different order.