Skip to content
← Back to rules

eslint/no-case-declarations Pedantic

💡 A suggestion is available for this rule.

作用

禁止在 case 子句中进行词法声明。

为什么不好?

原因是词法声明在整个 switch 块中都是可见的,但仅在被赋值时才会初始化,而这种情况只有在执行到定义它的 case 时才会发生。

示例

此规则 错误 代码示例:

javascript
switch (foo) {
  case 1:
    let x = 1;
    break;
  case 2:
    const y = 2;
    break;
  case 3:
    function f() {}
    break;
  default:
    class C {}
}

此规则 正确 代码示例:

javascript
switch (foo) {
  case 1: {
    let x = 1;
    break;
  }
  case 2: {
    const y = 2;
    break;
  }
  case 3: {
    function f() {}
    break;
  }
  default: {
    class C {}
  }
}

使用方法

To enable this rule using the config file or in the CLI, you can use:

json
{
  "rules": {
    "no-case-declarations": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  rules: {
    "no-case-declarations": "error",
  },
});
bash
oxlint --deny no-case-declarations

版本

此规则是在 v0.0.4 中添加的。

参考资料