switch-exhaustiveness-check
Require switch-case statements to be exhaustive.
在 TypeScript 中使用联合类型或枚举时,通常需要编写一个 switch
语句,该语句旨在包含联合或枚举中每种可能类型的 case
。但是,如果联合类型或枚举发生更改,很容易忘记修改案例以适应任何新类型。
¥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 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.
此规则报告何时类定义名为 switch
的方法或接口定义名为 default
的方法。
¥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.
- Flat Config
- Legacy Config
export default tseslint.config({
rules: {
"@typescript-eslint/switch-exhaustiveness-check": "error"
}
});
module.exports = {
"rules": {
"@typescript-eslint/switch-exhaustiveness-check": "error"
}
};
在线运行试试这个规则 ↗
选项
该规则接受以下选项:
type Options = [
{
/** If 'true', allow 'default' cases on switch statements with exhaustive cases. */
allowDefaultCaseForExhaustiveSwitch?: boolean;
/** If 'true', the 'default' clause is used to determine whether the switch statement is exhaustive for union type */
considerDefaultExhaustiveForUnions?: boolean;
/** Regular expression for a comment that can indicate an intentionally omitted default case. */
defaultCaseCommentPattern?: string;
/** If 'true', require a 'default' clause for switches on non-union types. */
requireDefaultForNonUnion?: boolean;
},
];
const defaultOptions: Options = [
{
allowDefaultCaseForExhaustiveSwitch: true,
considerDefaultExhaustiveForUnions: false,
requireDefaultForNonUnion: false,
},
];
¥Options
allowDefaultCaseForExhaustiveSwitch
If 'true', allow 'default' cases on switch statements with exhaustive cases. Default: true
.
如果设置为 false,此规则还将报告 switch
语句何时对联合中的所有内容都有案例,并且还包含 default
案例。因此,通过将此选项设置为 false,规则会变得更加严格。
¥If set to false, this rule will also report when a switch
statement has a case for everything in a union and also contains a default
case. Thus, by setting this option to false, the rule becomes stricter.
当联合类型的 switch
语句详尽无遗时,最后的 default
案例将是一种死代码。此外,如果向联合类型添加了新值并且你正在使用 considerDefaultExhaustiveForUnions
,则 default
将阻止 switch-exhaustiveness-check
规则报告 switch
语句中未处理的新情况。
¥When a switch
statement over a union type is exhaustive, a final default
case would be a form of dead code.
Additionally, if a new value is added to the union type and you're using considerDefaultExhaustiveForUnions
, a default
would prevent the switch-exhaustiveness-check
rule from reporting on the new case not being handled in the switch
statement.
allowDefaultCaseForExhaustiveSwitch
注意事项
¥allowDefaultCaseForExhaustiveSwitch
Caveats
如果值可能具有联合类型未表示的类型,则在详尽的 switch
语句中包含冗余的 default
情况有时会很有用。例如,在客户端和服务器之间可能存在版本不匹配的应用中, 运行较新软件版本的服务器可能会发送客户端较旧类型无法识别的值。
¥It can sometimes be useful to include a redundant default
case on an exhaustive switch
statement if it's possible for values to have types not represented by the union type.
For example, in applications that can have version mismatches between clients and servers, it's possible for a server running a newer software version to send a value not recognized by the client's older typings.
如果你的项目有少量故意冗余的 default
案例,你可能希望对每个案例使用一个 内联 ESLint 禁用注释。
¥If your project has a small number of intentionally redundant default
cases, you might want to use an inline ESLint disable comment for each of them.
如果你的项目有许多故意冗余的 default
案例,你可能希望禁用 allowDefaultCaseForExhaustiveSwitch
并将 default-case
核心 ESLint 规则 与 satisfies never
检查 一起使用。
¥If your project has many intentionally redundant default
cases, you may want to disable allowDefaultCaseForExhaustiveSwitch
and use the default-case
core ESLint rule along with a satisfies never
check.
requireDefaultForNonUnion
If 'true', require a 'default' clause for switches on non-union types. Default: false
.
如果设置为 true,此规则还将报告 switch
语句何时切换非联合类型(例如 number
或 string
)并且 switch
语句没有 default
案例。因此,通过将此选项设置为 true,规则会变得更加严格。
¥If set to true, this rule will also report when a switch
statement switches over a non-union type (like a number
or string
, for example) and that switch
statement does not have a default
case. Thus, by setting this option to true, the rule becomes stricter.
这通常是可取的,以便 number
和 string
开关将受到与其他开关相同的详尽检查。
¥This is generally desirable so that number
and string
switches will be subject to the same exhaustive checks that your other switches are.
带有 { requireDefaultForNonUnion: true }
的此规则的其他不正确代码示例:
¥Examples of additional incorrect code for this rule with { requireDefaultForNonUnion: true }
:
const value: number = Math.floor(Math.random() * 3);
switch (value) {
case 0:
return 0;
case 1:
return 1;
}
Open in Playground由于 value
是非联合类型,因此它要求 switch case 仅在启用 requireDefaultForNonUnion
时才具有默认子句。
¥Since value
is a non-union type it requires the switch case to have a default clause only with requireDefaultForNonUnion
enabled.
considerDefaultExhaustiveForUnions
If 'true', the 'default' clause is used to determine whether the switch statement is exhaustive for union type Default: false
.
如果设置为 true,则包含 default
案例的联合类型的 switch
语句被认为是详尽无遗的。否则,规则强制使用它们自己的显式 case
明确处理联合类型的每个组成部分。如果你想确保添加到联合中的每个值都得到显式处理,则保持此选项禁用会很有用,default
情况保留用于报告错误。
¥If set to true, a switch
statement over a union type that includes a default
case is considered exhaustive.
Otherwise, the rule enforces explicitly handling every constituent of the union type with their own explicit case
.
Keeping this option disabled can be useful if you want to make sure every value added to the union receives explicit handling, with the default
case reserved for reporting an error.
此规则使用 { considerDefaultExhaustiveForUnions: true }
的其他正确代码示例:
¥Examples of additional correct code with { considerDefaultExhaustiveForUnions: true }
:
declare const literal: 'a' | 'b';
switch (literal) {
case 'a':
break;
default:
break;
}
Open in PlaygrounddefaultCaseCommentPattern
Regular expression for a comment that can indicate an intentionally omitted default case.
默认:/^no default$/iu
。
¥Default: /^no default$/iu
.
有时最好只省略某些 switch 语句的默认情况。对于这些情况,可以为此规则提供一个注释模式,允许该注释代替 default:
。
¥It can sometimes be preferable to omit the default case for only some switch statements.
For those situations, this rule can be given a pattern for a comment that's allowed to take the place of a default:
.
此规则使用 { defaultCaseCommentPattern: "^skip\\sdefault" }
的其他正确代码示例:
¥Examples of additional correct code with { defaultCaseCommentPattern: "^skip\\sdefault" }
:
declare const value: 'a' | 'b';
switch (value) {
case 'a':
break;
// skip default
}
Open in Playground示例
¥Examples
当 switch 没有详尽的案例时,要么填写所有案例,要么添加默认值(如果启用了 considerDefaultExhaustiveForUnions
)将解决规则的投诉。
¥When the switch doesn't have exhaustive cases, either filling them all out or adding a default (if you have considerDefaultExhaustiveForUnions
enabled) will address the rule's complaint.
以下是一些使用字面量联合的代码示例:
¥Here are some examples of code working with a union of literals:
- ❌ Incorrect
- ✅ Correct (Exhaustive)
- ✅ Correct (Defaulted)
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 Playgroundtype 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;
}
Open in Playground// requires `considerDefaultExhaustiveForUnions` to be set to true
type Day =
| 'Monday'
| 'Tuesday'
| 'Wednesday'
| 'Thursday'
| 'Friday'
| 'Saturday'
| 'Sunday';
declare const day: Day;
let result = 0;
switch (day) {
case 'Monday':
result = 1;
break;
default:
result = 42;
}
Open in Playground同样,以下是一些使用枚举的代码示例:
¥Likewise, here are some examples of code working with an enum:
- ❌ Incorrect
- ✅ Correct (Exhaustive)
- ✅ Correct (Defaulted)
enum Fruit {
Apple,
Banana,
Cherry,
}
declare const fruit: Fruit;
switch (fruit) {
case Fruit.Apple:
console.log('an apple');
break;
}
Open in Playgroundenum Fruit {
Apple,
Banana,
Cherry,
}
declare const fruit: Fruit;
switch (fruit) {
case Fruit.Apple:
console.log('an apple');
break;
case Fruit.Banana:
console.log('a banana');
break;
case Fruit.Cherry:
console.log('a cherry');
break;
}
Open in Playground// requires `considerDefaultExhaustiveForUnions` to be set to true
enum Fruit {
Apple,
Banana,
Cherry,
}
declare const fruit: Fruit;
switch (fruit) {
case Fruit.Apple:
console.log('an apple');
break;
default:
console.log('a fruit');
break;
}
Open in Playground何时不使用它
¥When Not To Use It
如果你不经常对具有许多部分的联合类型或枚举使用 switch
,或者故意希望省略某些部分,则此规则可能不适合你。
¥If you don't frequently switch
over union types or enums with many parts, or intentionally wish to leave out some parts, this rule may not be for you.
Type checked lint rules are more powerful than traditional lint rules, but also require configuring type checked linting.
See Troubleshooting > Linting with Type Information > Performance if you experience performance degradations after enabling type checked rules.
'## 资源'