Skip to content

useExhaustiveSwitchCases

¥Summary

¥How to configure

biome.json
{
"linter": {
"rules": {
"nursery": {
"useExhaustiveSwitchCases": "error"
}
}
}
}

¥Description

要求 switch-case 语句必须穷尽所有情况。

¥Require switch-case statements to be exhaustive.

在 TypeScript 中使用联合类型时,通常需要编写 switch 语句,其中包含每个可能变体的 case。但是,如果联合类型发生更改,很容易忘记修改这些情况以适应任何新类型。

¥When working with union types in TypeScript, it’s common to want to write a switch statement intended to contain a case for each possible variant. However, if the union type changes, it’s easy to forget to modify the cases to account for any new types.

此规则会在以下情况下报告 switch 语句对类型为字面量联合类型的值缺少任何字面量类型的 case 语句且没有 default 子句时发出警告。

¥This rule reports when a switch statement over a value typed as a union of literals lacks a case for any of those literal types and does not have a default clause.

¥Examples

¥Invalid

invalid.ts
type Day =
| 'Monday'
| 'Tuesday'
| 'Wednesday'
| 'Thursday'
| 'Friday'
| 'Saturday'
| 'Sunday';
declare const day: Day;
let result = 0;
switch (day) {
case 'Monday':
result = 1;
break;
}
/invalid.ts:13:1 lint/nursery/useExhaustiveSwitchCases  FIXABLE  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

The switch statement is not exhaustive.

11 │ let result = 0;
12 │
> 13 │ switch (day) {
^^^^^^^^^^^^^^
> 14 │ case ‘Monday’:
> 15 │ result = 1;
> 16 │ break;
> 17 │ }
^
18 │

Some variants of the union type are not handled here.

These cases are missing:

- “Tuesday”
- “Wednesday”
- “Thursday”
- “Friday”
- “Saturday”
- “Sunday”

Unsafe fix: Add the missing cases to the switch statement.

14 14 case ‘Monday’:
15 15 result = 1;
16 - ····break;
16+ ····break;
17+ ··case·Tuesday:·throw·new·Error(TODO:·Not·implemented·yet);
18+ ··case·Wednesday:·throw·new·Error(TODO:·Not·implemented·yet);
19+ ··case·Thursday:·throw·new·Error(TODO:·Not·implemented·yet);
20+ ··case·Friday:·throw·new·Error(TODO:·Not·implemented·yet);
21+ ··case·Saturday:·throw·new·Error(TODO:·Not·implemented·yet);
22+ ··case·Sunday:·throw·new·Error(TODO:·Not·implemented·yet);
17 23 }
18 24

¥Valid

valid.ts
type Day =
| 'Monday'
| 'Tuesday'
| 'Wednesday'
| 'Thursday'
| 'Friday'
| 'Saturday'
| 'Sunday';
declare const day: 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;
}

¥Related links