eslint/no-fallthrough Pedantic
它的作用
禁止 case 语句的贯穿
该规则旨在消除一个 case 意外贯穿到另一个 case 的情况。因此,它会标记任何未通过注释标明的贯穿场景。
为什么这不好?
JavaScript 中的 switch 语句是语言里更容易出错的结构之一,部分原因在于它能够从一个 case “贯穿”到下一个 case。例如:
js
switch (foo) {
case 1:
doSomething();
case 2:
doSomethingElse();
}在这个例子中,如果 foo 是 1,那么执行会流经这两个 case,因为第一个会贯穿到第二个。你可以通过使用 break 来避免这一点,如下所示:
js
switch (foo) {
case 1:
doSomething();
break;
case 2:
doSomethingElse();
}当你不希望发生贯穿时,这样做没问题,但如果贯穿是有意为之,又没有办法在语言层面标明这一点。最佳实践是始终使用注释来说明贯穿是有意的,该注释应匹配 `/falls?\s?through/i`` 正则表达式,但不能是指令:
js
switch (foo) {
case 1:
doSomething();
// 跌穿
case 2:
doSomethingElse();
}
switch (foo) {
case 1:
doSomething();
// fall through
case 2:
doSomethingElse();
}
switch (foo) {
case 1:
doSomething();
// fallsthrough
case 2:
doSomethingElse();
}
switch (foo) {
case 1: {
doSomething();
// 跌穿
}
case 2: {
doSomethingElse();
}
}在这个例子中,对预期行为不会有任何困惑。很明显,第一个 case 是要贯穿到第二个 case 的。
示例
此规则的错误代码示例:
js
switch (foo) {
case 1:
doSomething();
case 2:
doSomething();
}此规则的正确代码示例:
js
switch (foo) {
case 1:
doSomething();
break;
case 2:
doSomething();
}
function bar(foo) {
switch (foo) {
case 1:
doSomething();
return;
case 2:
doSomething();
}
}
switch (foo) {
case 1:
doSomething();
throw new Error("Boo!");
case 2:
doSomething();
}
switch (foo) {
case 1:
case 2:
doSomething();
}
switch (foo) {
case 1:
case 2:
doSomething();
}
switch (foo) {
case 1:
doSomething();
// 跌穿
case 2:
doSomething();
}
switch (foo) {
case 1: {
doSomething();
// 跌穿
}
case 2: {
doSomethingElse();
}
}请注意,在这些示例中,最后一个 case 语句不会产生警告,因为没有可以贯穿进入的目标。
配置
此规则接受一个包含以下属性的配置对象:
allowEmptyCase
type: boolean
default: false
是否允许空的 case 子句贯穿。
commentPattern
type: string
用于匹配贯穿注释的自定义正则表达式模式。
reportUnusedFallthroughComment
type: boolean
default: false
是否报告未使用的贯穿注释。
如何使用
To enable this rule using the config file or in the CLI, you can use:
json
{
"rules": {
"no-fallthrough": "error"
}
}ts
import { defineConfig } from "oxlint";
export default defineConfig({
rules: {
"no-fallthrough": "error",
},
});bash
oxlint --deny no-fallthrough版本
此规则在 v0.0.14 中添加。
