问题
In Javascript, I sometimes accidentally write:
if (obj.method) { // <-- bad
...
}
instead of
if (obj.method()) { // <-- good
...
}
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.
回答1:
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!
Example: https://www.typescriptlang.org/play/#code/CYUwxgNghgTiAEYD2A7AzgF3kgRgKwC54BveAWxAwAslgAKASiJySQhChXgF8AoXgJYAzeHVx4AdBWq0GJXvEXxe3IA
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 your
if
conditions are booleans (i.e. it would catch this case because the function is not a boolean).
来源:https://stackoverflow.com/questions/62826432/is-there-a-typescript-eslint-rule-that-alerts-you-when-you-use-a-method-as-a-boo