版本

no-unsafe-negation

不允許否定關係運算子的左運算元

建議

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

💡 有建議

此規則報告的一些問題可以透過編輯器的建議手動修復

正如開發人員可能會在想要表達總和的負數時輸入 -a + b 而非 -(a + b) 一樣,他們可能會錯誤地輸入 !key in object,而幾乎可以肯定他們的意思是 !(key in object) 來測試一個鍵是否不在物件中。 !obj instanceof Ctor 也是類似的情況。

規則細節

此規則不允許否定以下關係運算子的左運算元

此規則的不正確程式碼範例

在線上編輯器中開啟
/*eslint no-unsafe-negation: "error"*/

if (!key in object) {
    // operator precedence makes it equivalent to (!key) in object
    // and type conversion makes it equivalent to (key ? "false" : "true") in object
}

if (!obj instanceof Ctor) {
    // operator precedence makes it equivalent to (!obj) instanceof Ctor
    // and it equivalent to always false since boolean values are not objects.
}

此規則的正確程式碼範例

在線上編輯器中開啟
/*eslint no-unsafe-negation: "error"*/

if (!(key in object)) {
    // key is not in object
}

if (!(obj instanceof Ctor)) {
    // obj is not an instance of Ctor
}

例外

對於少數情況下有意否定左運算元的情況,此規則允許例外。如果整個否定明確地用括號括起來,則該規則不會報告問題。

此規則的正確程式碼範例

在線上編輯器中開啟
/*eslint no-unsafe-negation: "error"*/

if ((!foo) in object) {
    // allowed, because the negation is explicitly wrapped in parentheses
    // it is equivalent to (foo ? "false" : "true") in object
    // this is allowed as an exception for rare situations when that is the intended meaning
}

if(("" + !foo) in object) {
    // you can also make the intention more explicit, with type conversion
}

此規則的不正確程式碼範例

在線上編輯器中開啟
/*eslint no-unsafe-negation: "error"*/

if (!(foo) in object) {
    // this is not an allowed exception
}

選項

此規則有一個物件選項

  • "enforceForOrderingRelations": false (預設值) 允許否定排序關係運算子 (<><=>=) 的左側
  • "enforceForOrderingRelations": true 不允許否定排序關係運算子的左側

enforceForOrderingRelations

將此選項設定為 true 時,該規則還會強制執行以下運算子

  • < 運算子。
  • > 運算子。
  • <= 運算子。
  • >= 運算子。

目的是避免諸如 ! a < b (等同於 (a ? 0 : 1) < b) 的表達式,而真正意圖的是 !(a < b)

使用 { "enforceForOrderingRelations": true } 選項時,此規則的其他不正確程式碼範例

在線上編輯器中開啟
/*eslint no-unsafe-negation: ["error", { "enforceForOrderingRelations": true }]*/

if (! a < b) {}

while (! a > b) {}

foo = ! a <= b;

foo = ! a >= b;

何時不使用它

如果您不想通知不安全的邏輯否定,則可以安全地停用此規則。

由 TypeScript 處理

當使用 TypeScript 時,停用此規則是安全的,因為 TypeScript 的編譯器會強制執行此檢查。

版本

此規則是在 ESLint v3.3.0 中引入的。

資源

變更語言