no-unsafe-negation
禁用否定关系运算符的左操作数
正如开发人员可能会将 -a + b
误写成 -(a + b)
来表示负数之和一样,他们可能会错误地输入 !key in object
,而他们几乎肯定是指 !(key in object)
来测试键是否不在对象中。!obj instanceof Ctor
类似。
规则详情
此规则禁止否定以下关系运算符的左操作数
此规则的错误代码示例
在 Playground 中打开
/*eslint no-unsafe-negation: "error"*/
if ( in object) {
// operator precedence makes it equivalent to (!key) in object
// and type conversion makes it equivalent to (key ? "false" : "true") in object
}
if ( instanceof Ctor) {
// operator precedence makes it equivalent to (!obj) instanceof Ctor
// and it equivalent to always false since boolean values are not objects.
}
此规则的正确代码示例
在 Playground 中打开
/*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
}
例外情况
对于极少数情况下需要否定左操作数的情况,此规则允许例外。如果整个否定显式地用括号括起来,则该规则不会报告问题。
此规则的正确代码示例
在 Playground 中打开
/*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
}
此规则的错误代码示例
在 Playground 中打开
/*eslint no-unsafe-negation: "error"*/
if ( in object) {
// this is not an allowed exception
}
选项
此规则有一个对象选项
"enforceForOrderingRelations": false
(默认) 允许否定排序关系运算符 (<
,>
,<=
,>=
) 的左侧"enforceForOrderingRelations": true
禁止否定排序关系运算符的左侧
enforceForOrderingRelations
当此选项设置为 true
时,该规则还会对以下运算符强制执行
<
运算符。>
运算符。<=
运算符。>=
运算符。
目的是避免诸如 ! a < b
(等价于 (a ? 0 : 1) < b
) 这样的表达式,而真正想要的是 !(a < b)
。
当 { "enforceForOrderingRelations": true }
选项启用时,此规则的更多错误代码示例
在 Playground 中打开
/*eslint no-unsafe-negation: ["error", { "enforceForOrderingRelations": true }]*/
if ( < b) {}
while ( > b) {}
foo = <= b;
foo = >= b;
何时不使用
如果您不想通知不安全的逻辑否定,那么禁用此规则是安全的。
由 TypeScript 处理
当使用 TypeScript 时,禁用此规则是安全的,因为 TypeScript 的编译器会强制执行此检查。
版本
此规则在 ESLint v3.3.0 中引入。