Skip to content
← Back to rules

typescript/no-unnecessary-boolean-literal-compare 可疑

💭 This rule requires type information.
An auto-fix is available for this rule.

它的作用

此规则禁止对布尔字面量进行不必要的相等性比较。

为什么这是不好的?

当比较可以被消除时,将布尔值与布尔字面量进行比较是多余的。这类比较会使代码更冗长,但并未增加实际价值。

示例

以下为 错误 用法示例:

ts
declare const someCondition: boolean;

if (someCondition === true) {
  // ...
}

if (someCondition === false) {
  // ...
}

if (someCondition !== true) {
  // ...
}

if (someCondition !== false) {
  // ...
}

const result = someCondition == true;

以下为 正确 用法示例:

ts
declare const someCondition: boolean;

if (someCondition) {
  // ...
}

if (!someCondition) {
  // ...
}

// 与非布尔类型进行比较是允许的
declare const someValue: unknown;
if (someValue === true) {
  // ...
}

配置

此规则接受一个配置对象,包含以下属性:

allowComparingNullableBooleansToFalse

type: boolean

默认值: true

是否允许将可空布尔表达式与 false 进行比较。 当设为 false 时,若 xboolean | null,则 x === false 将被标记。

allowComparingNullableBooleansToTrue

type: boolean

默认值: true

是否允许将可空布尔表达式与 true 进行比较。 当设为 false 时,若 xboolean | null,则 x === true 将被标记。

如何使用

要通过配置文件或 CLI 启用 此规则,可以使用:

json
{
  "rules": {
    "typescript/no-unnecessary-boolean-literal-compare": "error"
  }
}
bash
oxlint --type-aware --deny typescript/no-unnecessary-boolean-literal-compare

参考资料