[英]ESLint + TypeScript + Stricter if statements
I've currently discovered a very subtle bug in my TypeScript project:我目前在我的 TypeScript 项目中发现了一个非常微妙的错误:
const makeDecision = (): Promise<boolean> => {
return Promise.resolve(false);
};
const shouldDoIt = makeDecision(); // Oops! I forgot the await
if (shouldDoIt) {
// do stuff
}
(I hand typed that just now, so there may be a mistake...) (我刚才是手写的,所以可能有错误......)
In this particular example, I forgot the await
keyword which caused shouldDoIt
to be a Promise
, rather than a boolean
.在这个特定示例中,我忘记了导致
shouldDoIt
成为Promise
而不是boolean
的await
关键字。 So, it'll always be truthy in a if
-statement.所以,它在
if
语句中总是真实的。 Because this is valid behavior for JavaScript, the TypeScript compiler doesn't complain a bit even though this was not my intention.因为这是 JavaScript 的有效行为,所以 TypeScript 编译器不会抱怨一点,即使这不是我的意图。 Obviously, computers don't magically know my intention, but compilers can be very strict if need-be.
显然,计算机不会神奇地知道我的意图,但如果需要,编译器可以非常严格。
Is there a way to either configure ESLint or the TypeScript compiler to be more strict about if-statements to only allow boolean
, rather than truthy types?有没有办法配置 ESLint 或 TypeScript 编译器对 if 语句更加严格,只允许
boolean
,而不是真实的类型? Ideally, I'd love the compiler or ESLint to fail for statements like:理想情况下,我希望编译器或 ESLint 因以下语句而失败:
if ("a string") {
}
if (null) {
}
if (someNumber) {
}
The typescript-eslint rule strict-boolean-expressions
does what you're looking for. typescript-eslint 规则
strict-boolean-expressions
可以满足您的需求。 Additionally, the no-unnecessary-condition
rule would have caught your case too.此外,
no-unnecessary-condition
规则也会抓住你的情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.