Skip to content
← Back to rules

typescript/strict-boolean-expressions Pedantic

💭 This rule requires type information.
🚧 An auto-fix is planned for this rule, but not implemented at this time.

它的作用

禁止在布尔表达式中使用某些类型。

为什么这不好?

禁止在期望布尔值的表达式中使用非布尔类型。 booleannever 类型始终允许。可通过选项配置在布尔上下文中被视为安全的其他类型。

会检查以下节点:

  • !&&|| 运算符的参数
  • 条件表达式中的条件(cond ? x : y
  • ifforwhiledo-while 语句的条件。

示例

以下是此规则的错误代码示例:

ts
const str = "hello";
if (str) {
  console.log("string");
}

const num = 42;
if (num) {
  console.log("number");
}

const obj = { foo: "bar" };
if (obj) {
  console.log("object");
}

declare const maybeString: string | undefined;
if (maybeString) {
  console.log(maybeString);
}

const result = str && num;
const ternary = str ? "yes" : "no";

以下是此规则的正确代码示例:

ts
const str = "hello";
if (str !== "") {
  console.log("string");
}

const num = 42;
if (num !== 0) {
  console.log("number");
}

const obj = { foo: "bar" };
if (obj !== null) {
  console.log("object");
}

declare const maybeString: string | undefined;
if (maybeString !== undefined) {
  console.log(maybeString);
}

const bool = true;
if (bool) {
  console.log("boolean");
}

配置

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

allowAny

type: boolean

default: false

是否允许在布尔上下文中使用 any 类型。

allowNullableBoolean

type: boolean

default: false

是否允许在布尔上下文中使用可空布尔类型(例如 boolean | null)。

allowNullableEnum

type: boolean

default: false

是否允许在布尔上下文中使用可空枚举类型。

allowNullableNumber

type: boolean

default: false

是否允许在布尔上下文中使用可空数字类型(例如 number | null)。

allowNullableObject

type: boolean

default: true

是否允许在布尔上下文中使用可空对象类型。

allowNullableString

type: boolean

default: false

是否允许在布尔上下文中使用可空字符串类型(例如 string | null)。

allowNumber

type: boolean

default: true

是否允许在布尔上下文中使用数字类型(检查非零数字)。

allowString

type: boolean

default: true

是否允许在布尔上下文中使用字符串类型(检查非空字符串)。

如何使用

To enable this rule using the config file or in the CLI, you can use:

json
{
  "options": {
    "typeAware": true
  },
  "rules": {
    "typescript/strict-boolean-expressions": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  options: { typeAware: true },
  rules: {
    "typescript/strict-boolean-expressions": "error",
  },
});
bash
oxlint --type-aware --deny typescript/strict-boolean-expressions

版本

此规则在 v1.25.0 中添加。

参考资料