Skip to content
← Back to rules

typescript/no-extra-non-null-assertion Correctness

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;
}

如何使用

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

json
{
  "rules": {
    "typescript/no-extra-non-null-assertion": "error"
  }
}
ts
import { defineConfig } from "oxlint";

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

版本

此规则在 v0.0.6 中添加。

参考资料