Skip to content
← Back to rules

typescript/no-non-null-assertion Restriction

🚧 An auto-fix is planned for this rule, but not implemented at this time.

作用

禁止使用 ! 后缀运算符进行非空断言。

为什么这不好?

TypeScript 的 ! 非空断言运算符会向类型系统断言某个表达式是非空的,也就是不是 nullundefined。使用断言向类型系统告知新信息,往往表明代码并非完全类型安全。通常更好的做法是组织程序逻辑,让 TypeScript 能够理解值何时可能为可空。

示例

此规则的错误代码示例:

ts
x!;
x!.y;
x.y!;

此规则的正确代码示例:

ts
x;
x?.y;
x.y;

如何使用

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

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

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

版本

此规则于 v0.5.0 中添加。

参考资料