Skip to content
← Back to rules

typescript/no-non-null-asserted-nullish-coalescing 限制

An auto-fix is available for this rule.

它的作用

禁止在空值合并操作符的左操作数中使用非空断言。

为什么这是不好的?

?? 空值合并运行时操作符允许在处理 nullundefined 时提供默认值。在空值合并操作符的左操作数中使用 ! 非空断言类型操作符是冗余的,很可能表明程序员出现了错误或对这两个操作符的混淆。

示例

此规则的 错误 代码示例:

ts
foo! ?? bar;
foo.bazz! ?? bar;
foo!.bazz! ?? bar;
foo()! ?? bar;

let x!: string;
x! ?? "";

let x: string;
x = foo();
x! ?? "";

此规则的 正确 代码示例:

ts
foo ?? bar;
foo ?? bar!;
foo!.bazz ?? bar;
foo!.bazz ?? bar!;
foo() ?? bar;
ts
// 这被认为是正确代码,因为用户无法满足该条件。
let x: string;
x! ?? "";

如何使用

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

json
{
  "rules": {
    "typescript/no-non-null-asserted-nullish-coalescing": "error"
  }
}
bash
oxlint --deny typescript/no-non-null-asserted-nullish-coalescing

参考资料