Skip to content
← Back to rules

typescript/prefer-nullish-coalescing 严格

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

它的作用

强制使用空值合并操作符(??)而非逻辑或(||)或条件表达式,当左侧操作数可能为 nullundefined 时。

为什么这是个问题?

|| 操作符在左侧为任意假值(false0''nullundefinedNaN)时返回右侧表达式。这可能导致意外行为,特别是当你仅希望对 nullundefined 提供默认值时。

空值合并操作符(??)仅在左侧为 nullundefined 时才返回右侧表达式,使意图更清晰,并避免了其他假值带来的错误。

示例

以下为该规则的 错误 用法示例:

ts
declare const x: string | null;

// 使用 || 时,?? 更合适
const foo = x || "default";

// 可以使用 ?? 的三元表达式
const bar = x !== null && x !== undefined ? x : "default";
const baz = x != null ? x : "default";

// 可以使用 ?? 的 if 语句
let value = "default";
if (x !== null && x !== undefined) {
  value = x;
}

以下为该规则的 正确 用法示例:

ts
declare const x: string | null;

// 使用空值合并
const foo = x ?? "default";

// || 在你想要假值行为时是合适的
declare const y: string;
const bar = y || "default";

// 布尔值转换(可通过 ignoreBooleanCoercion 忽略)
const bool = Boolean(x || y);

配置

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

ignoreBooleanCoercion

type: boolean

default: false

是否忽略 Boolean 构造函数的参数。

ignoreConditionalTests

type: boolean

default: true

是否忽略位于条件测试中的情况。

ignoreIfStatements

type: boolean

default: false

是否忽略任何可以使用空值合并操作符简化的 if 语句。

ignoreMixedLogicalExpressions

type: boolean

default: false

是否忽略属于混合逻辑表达式(包含 &&)的任何逻辑与表达式。

ignorePrimitives

type: boolean

表示 ignorePrimitives 在 JSON 中可指定的不同方式。可以是:

  • true - 忽略所有原始类型
  • 一个对象,指定要忽略的原始类型

ignoreTernaryTests

type: boolean

default: false

是否忽略任何可以使用空值合并操作符简化的三元表达式。

如何使用

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

json
{
  "rules": {
    "typescript/prefer-nullish-coalescing": "error"
  }
}
bash
oxlint --type-aware --deny typescript/prefer-nullish-coalescing

参考资料