Skip to content
← Back to rules

eslint/no-ternary Style

作用

不允许使用三元运算符。

为什么这不好?

三元运算符用于根据条件为变量赋值。有些人认为使用三元运算符会导致代码不够清晰。

示例

以下是此规则的错误代码示例:

javascript
var foo = isBar ? baz : qux;
javascript
function quux() {
  return foo ? bar() : baz();
}

以下是此规则的正确代码示例:

javascript
let foo;

if (isBar) {
  foo = baz;
} else {
  foo = qux;
}
javascript
function quux() {
  if (foo) {
    return bar();
  } else {
    return baz();
  }
}

如何使用

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

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

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

版本

此规则于 v0.2.14 中添加。

参考资料