no-extra-boolean-cast
禁用不必要的布尔类型转换
✅ 推荐
在配置文件中使用 @eslint/js
中的 recommended
配置启用此规则
🔧 可修复
此规则报告的某些问题可以通过 --fix
命令行选项自动修复
❄️ 冻结
此规则目前处于冻结状态,不接受功能请求。
在诸如 if
语句的测试等上下文中,表达式的结果已经被强制转换为布尔值,因此通过双重否定 (!!
) 或 Boolean
调用转换为布尔值是不必要的。例如,以下 if
语句是等效的
if (!!foo) {
// ...
}
if (Boolean(foo)) {
// ...
}
if (foo) {
// ...
}
规则详情
此规则禁止不必要的布尔类型转换。
此规则的错误代码示例
在 Playground 中打开
/*eslint no-extra-boolean-cast: "error"*/
const foo = !;
const foo1 = ? baz : bat;
const foo2 = Boolean();
const foo3 = new Boolean();
if () {
// ...
}
if () {
// ...
}
while () {
// ...
}
do {
// ...
} while ();
for (; ; ) {
// ...
}
此规则的正确代码示例
在 Playground 中打开
/*eslint no-extra-boolean-cast: "error"*/
const foo = !!bar;
const foo1 = Boolean(bar);
function qux() {
return !!bar;
}
foo = bar ? !!baz : !!bat;
选项
此规则有一个对象选项
- 当
"enforceForInnerExpressions"
设置为true
时,除了检查默认上下文之外,还会检查在结果在布尔上下文中使用的表达式中是否存在额外的布尔类型转换。请参见以下示例。默认值为false
,这意味着默认情况下,此规则不会警告内部表达式中额外的布尔类型转换。
已弃用:对象属性 enforceForLogicalOperands
已弃用 (eslint#18222)。请使用 enforceForInnerExpressions
代替。
enforceForInnerExpressions
启用 "enforceForInnerExpressions"
选项设置为 true
时,此规则的错误代码示例
在 Playground 中打开
/*eslint no-extra-boolean-cast: ["error", {"enforceForInnerExpressions": true}]*/
if ( || bar) {
//...
}
while ( && bar) {
//...
}
if (( || bar) && ) {
//...
}
const foo = new Boolean( || baz);
foo && ? baz : bat;
const ternaryBranches = Boolean(bar ? : bat);
const nullishCoalescingOperator = Boolean(bar ?? );
const commaOperator = Boolean((bar, baz, ));
// another comma operator example
for (let i = 0; console.log(i), ; i++) {
// ...
}
启用 "enforceForInnerExpressions"
选项设置为 true
时,此规则的正确代码示例
在 Playground 中打开
/*eslint no-extra-boolean-cast: ["error", {"enforceForInnerExpressions": true}]*/
// Note that `||` and `&&` alone aren't a boolean context for either operand
// since the resultant value need not be a boolean without casting.
const foo = !!bar || baz;
if (foo || bar) {
//...
}
while (foo && bar) {
//...
}
if ((foo || bar) && baz) {
//...
}
const foo1 = new Boolean(bar || baz);
foo && bar ? baz : bat;
const ternaryBranches = Boolean(bar ? baz : bat);
const nullishCoalescingOperator = Boolean(bar ?? baz);
const commaOperator = Boolean((bar, baz, bat));
// another comma operator example
for (let i = 0; console.log(i), i < 10; i++) {
// ...
}
// comma operator in non-final position
Boolean((Boolean(bar), baz, bat));
版本
此规则在 ESLint v0.4.0 中引入。