Skip to content
← Back to rules

unicorn/no-nested-ternary Style

🛠️ An auto-fix is available for this rule for some violations.

作用

此规则不允许深度嵌套的三元表达式。 仅嵌套一层且用括号包裹的三元表达式是允许的。

为什么这不好?

嵌套三元表达式会使代码更难理解。

示例

此规则的错误代码示例:

javascript
const foo = i > 5 ? (i < 100 ? true : false) : true;
const foo = i > 5 ? true : i < 100 ? true : i < 1000 ? true : false;

此规则的正确代码示例:

javascript
const foo = i > 5 ? (i < 100 ? true : false) : true;
const foo = i > 5 ? (i < 100 ? true : false) : i < 100 ? true : false;

如何使用

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

json
{
  "rules": {
    "unicorn/no-nested-ternary": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  rules: {
    "unicorn/no-nested-ternary": "error",
  },
});
bash
oxlint --deny unicorn/no-nested-ternary

版本

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

参考资料