unicorn/prefer-ternary Style
它的作用
优先使用三元表达式,而不是简单的 if/else 语句。
这有什么问题?
对于同样的操作,简单的 if/else 分支用三元表达式表示时,通常更简短,也更清晰。
示例
此规则的错误代码示例:
js
if (test) {
return a;
} else {
return b;
}此规则的正确代码示例:
js
return test ? a : b;配置
此规则接受以下字符串值之一:
"always"
当各分支可以安全合并时,始终强制使用三元表达式。
"only-single-line"
仅当条件以及两个分支都是单行时,才强制使用三元表达式。
如何使用
To enable this rule using the config file or in the CLI, you can use:
json
{
"rules": {
"unicorn/prefer-ternary": "error"
}
}ts
import { defineConfig } from "oxlint";
export default defineConfig({
rules: {
"unicorn/prefer-ternary": "error",
},
});bash
oxlint --deny unicorn/prefer-ternary版本
此规则已在 v1.50.0 中添加。
