【问题标题】:Is there a TSLint/ESLint rule to prevent (boolean === true) type of comparisons?是否有 TSLint/ESLint 规则来防止 (boolean === true) 类型的比较?
【发布时间】:2016-05-15 05:28:15
【问题描述】:

是否有 TSLint/ESLint 规则来防止不必要的布尔比较,例如:

if (result === false) {
  // do something
} 

【问题讨论】:

  • 我不知道执行此操作的内置规则或自定义规则。不过,这听起来像是一个合理的功能要求!
  • 我已经向 core eslint 提交了一个规则请求:github.com/eslint/eslint/issues/9743

标签: eslint tslint


【解决方案1】:

TSLint 支持规则 no-boolean-literal-compare,它就是这样做的。

rules 数组中的"no-boolean-literal-compare": true 将启用此功能。

文档链接:https://palantir.github.io/tslint/rules/no-boolean-literal-compare/

【讨论】:

    【解决方案2】:

    您目前可以使用 ESLint 完成此操作:

    "no-restricted-syntax": [
        "error",
         {
            "selector": "BinaryExpression[operator=/^(==|===|!=|!==)$/][left.raw=/^(true|false)$/], BinaryExpression[operator=/^(==|===|!=|!==)$/][right.raw=/^(true|false)$/]",
            "message": "Don't compare for equality against boolean literals"
         }
    ]
    

    当其中一个(或两个)操作数是布尔文字时,选择器不允许使用=====!=!==


    Source

    【讨论】:

    • 谢谢!这正是我所需要的:D
    猜你喜欢
    • 2020-06-05
    • 2019-06-16
    • 2020-02-26
    • 2021-12-21
    • 2020-05-25
    • 1970-01-01
    • 2020-03-09
    • 2019-05-29
    • 2019-10-20
    相关资源
    最近更新 更多