Skip to content
← Back to rules

eslint/no-lonely-if Pedantic

🚧 An auto-fix is planned for this rule, but not implemented at this time.

它的作用

禁止在 else 块中仅包含 if 语句。

为什么这不好?

if 语句是 else 块中的唯一语句时,通常使用 else if 会更清晰。

示例

此规则的错误代码示例:

js
if (condition) {
  // ...
} else {
  if (anotherCondition) {
    // ...
  }
}
js
if (condition) {
  // ...
} else {
  if (anotherCondition) {
    // ...
  } else {
    // ...
  }
}

此规则的正确代码示例:

js
if (condition) {
  // ...
} else if (anotherCondition) {
  // ...
}
js
if (condition) {
  // ...
} else if (anotherCondition) {
  // ...
} else {
  // ...
}
js
if (condition) {
  // ...
} else {
  if (anotherCondition) {
    // ...
  }
  doSomething();
}

如何使用

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

json
{
  "rules": {
    "no-lonely-if": "error"
  }
}
ts
import { defineConfig } from "oxlint";

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

版本

此规则添加于 v0.16.0。

参考资料