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

类型:boolean

默认值:false

是否允许布尔上下文中的 any 类型。

allowNullableBoolean

类型:boolean

默认值:false

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

allowNullableEnum

类型:boolean

默认值:false

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

allowNullableNumber

类型:boolean

默认值:false

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

allowNullableObject

类型:boolean

默认值:true

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

allowNullableString

类型:boolean

默认值:false

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

allowNumber

类型:boolean

默认值:true

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

allowString

类型:boolean

默认值: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。

参考