版本

no-extra-boolean-cast

不允許不必要的布林轉換

推薦

設定檔中使用 @eslint/jsrecommended 設定會啟用此規則

🔧 可修正

此規則報告的某些問題可由 --fix 命令列選項自動修正

在像是 if 語句的測試,運算式的結果會自動轉換為布林值的上下文,透過雙重否定 (!!) 或 Boolean 呼叫來轉換為布林值是不必要的。例如,這些 if 語句是等效的

if (!!foo) {
    // ...
}

if (Boolean(foo)) {
    // ...
}

if (foo) {
    // ...
}

規則詳細資訊

此規則不允許不必要的布林轉換。

此規則的錯誤程式碼範例

在線上執行環境開啟
/*eslint no-extra-boolean-cast: "error"*/

var foo = !!!bar;

var foo = !!bar ? baz : bat;

var foo = Boolean(!!bar);

var foo = new Boolean(!!bar);

if (!!foo) {
    // ...
}

if (Boolean(foo)) {
    // ...
}

while (!!foo) {
    // ...
}

do {
    // ...
} while (Boolean(foo));

for (; !!foo; ) {
    // ...
}

此規則的正確程式碼範例

在線上執行環境開啟
/*eslint no-extra-boolean-cast: "error"*/

var foo = !!bar;
var foo = Boolean(bar);

function qux() {
    return !!bar;
}

var foo = bar ? !!baz : !!bat;

選項

此規則具有物件選項

  • "enforceForInnerExpressions" 設定為 true 時,除了檢查預設上下文之外,還會檢查在布林上下文中使用結果的運算式中是否存在額外的布林轉換。請參閱以下範例。預設值為 false,表示此規則預設不會警告內部運算式中的額外布林轉換。

已棄用: 物件屬性 enforceForLogicalOperands 已棄用 (eslint#18222)。請改用 enforceForInnerExpressions

enforceForInnerExpressions

"enforceForInnerExpressions" 選項設定為 true 時,此規則的錯誤程式碼範例

在線上執行環境開啟
/*eslint no-extra-boolean-cast: ["error", {"enforceForInnerExpressions": true}]*/

if (!!foo || bar) {
    //...
}

while (!!foo && bar) {
    //...
}

if ((!!foo || bar) && !!baz) {
    //...
}

var foo = new Boolean(!!bar || baz);

foo && Boolean(bar) ? baz : bat;

const ternaryBranches = Boolean(bar ? !!baz : bat);

const nullishCoalescingOperator = Boolean(bar ?? Boolean(baz));

const commaOperator = Boolean((bar, baz, !!bat));

// another comma operator example
for (let i = 0; console.log(i), Boolean(i < 10); i++) {
    // ...
}

"enforceForInnerExpressions" 選項設定為 true 時,此規則的正確程式碼範例

在線上執行環境開啟
/*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.
var foo = !!bar || baz;

if (foo || bar) {
    //...
}

while (foo && bar) {
    //...
}

if ((foo || bar) && baz) {
    //...
}

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

資源

變更語言