![](/img/trans.png)
[英]Is there an ESLint rule that checks the number of logical operators in a conditional expression?
[英]Is there ESLint or TSLint rule that checks that truthy/falsy logical operator is not applied to numbers?
我今天有一个错误,我意外地跳过了对函数的调用,因为我的变量是 0:
const foo: number | undefined = getFoo();
if(foo) {
// Will not be called if foo is zero
doSomething(foo);
}
这是我经常使用的一种模式,用于测试是否定义了变量。 这适用于一切,对象,数组,字符串......除了数字。
这不是我第一次遇到这样的错误。
是否有一条规则会提醒我,例如:
if(foo)
--- Warning, testing a number variable that can be defined, but equals to zero
一些会迫使我写的东西:
if(foo !== undefined)
它不太漂亮,但至少它具有正确的行为。
编辑:考虑到这一点后,类型string
和值""
(空字符串)似乎会出现同样的问题
tslint
有严格布尔表达式。
对于 Typescript ESLint(因为 TSLint 已被弃用),有一个与Zbigniew Zagórski在另一个答案中提到的同名规则: strict-boolean-expressions
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.