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 中引入。