Is there a typescript-eslint rule that alerts you when you use a method as a boolean?

南笙酒味 提交于 2021-02-11 16:27:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!