no-extra-boolean-cast
不允許不必要的布林轉換
在像是 if
語句的測試,運算式的結果會自動轉換為布林值的上下文,透過雙重否定 (!!
) 或 Boolean
呼叫來轉換為布林值是不必要的。例如,這些 if
語句是等效的
if (!!foo) {
// ...
}
if (Boolean(foo)) {
// ...
}
if (foo) {
// ...
}
規則詳細資訊
此規則不允許不必要的布林轉換。
此規則的錯誤程式碼範例
在線上執行環境開啟
/*eslint no-extra-boolean-cast: "error"*/
var foo = !;
var foo = ? baz : bat;
var foo = Boolean();
var foo = new Boolean();
if () {
// ...
}
if () {
// ...
}
while () {
// ...
}
do {
// ...
} while ();
for (; ; ) {
// ...
}
此規則的正確程式碼範例
在線上執行環境開啟
/*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 ( || bar) {
//...
}
while ( && bar) {
//...
}
if (( || bar) && ) {
//...
}
var 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
時,此規則的正確程式碼範例
在線上執行環境開啟
/*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 中引入。