Skip to content
← Back to rules

typescript/no-extra-non-null-assertion 正确性

This rule is turned on by default.
An auto-fix is available for this rule.

它的作用

禁止多余的非空断言。

为什么这是个问题?

TypeScript 中的 ! 非空断言操作符用于断言某个值的类型不包含 nullundefined。对同一值重复使用该操作符超过一次没有任何作用。

示例

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

ts
const foo: { bar: number } | null = null;
const bar = foo!!!.bar;
ts
function foo(bar: number | undefined) {
  const bar: number = bar!!!;
}
ts
function foo(bar?: { n: number }) {
  return bar!?.n;
}

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

ts
const foo: { bar: number } | null = null;
const bar = foo!.bar;
ts
function foo(bar: number | undefined) {
  const bar: number = bar!;
}
ts
function foo(bar?: { n: number }) {
  return bar?.n;
}

如何使用

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

json
{
  "rules": {
    "typescript/no-extra-non-null-assertion": "error"
  }
}
bash
oxlint --deny typescript/no-extra-non-null-assertion

参考资料