当您将方法用作布尔值时,是否存在打字稿夹住的规则会提醒您? [英] Is there a typescript-eslint rule that alerts you when you use a method as a boolean?
问题描述
在Javascript中,有时我会不小心写:
In Javascript, I sometimes accidentally write:
if (obj.method) { // <-- bad
...
}
代替
if (obj.method()) { // <-- good
...
}
鉴于typescript-eslint是typeaware,是否存在检测此用法的规则?我想说的是99/100次,我不是想将这种方法用作布尔值.
Given that typescript-eslint is typeaware, is there a rule that detects this usage? I would say that 99/100 times, I am not trying to use the method as a boolean.
推荐答案
如果打开打字机的 strictNullChecks
编译器选项(或全部使用 strict
编译器选项),TS会自动为您执行此特定检查!
If you turn on typescript's strictNullChecks
compiler option (or the catch-all strict
compiler option), TS will do this specific check for you automatically!
否则,如注释中提到的@ x4rf41一样,您可以使用短绒棉毛抓起它.
有两种打字稿保留规则,可以在这里为您提供帮助:
Otherwise as @x4rf41 mentioned in the comment, you can use a linter to catch it.
There are two typescript-eslint rules which will help you here:
no-unnecessary-condition
will ensure all your conditions are actually required (i.e. it would catch this case because the function is not nullable).strict-boolean-expressions
will ensure all yourif
conditions are booleans (i.e. it would catch this case because the function is not a boolean).
这篇关于当您将方法用作布尔值时,是否存在打字稿夹住的规则会提醒您?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!