Skip to content
← Back to rules

typescript/no-non-null-asserted-nullish-coalescing Restriction

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! ?? "";

如何使用

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

json
{
  "rules": {
    "typescript/no-non-null-asserted-nullish-coalescing": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  rules: {
    "typescript/no-non-null-asserted-nullish-coalescing": "error",
  },
});
bash
oxlint --deny typescript/no-non-null-asserted-nullish-coalescing

版本

此规则在 v0.5.0 中添加。

参考资料