typescript/no-non-null-assertion Restriction
作用
禁止使用 ! 后缀运算符进行非空断言。
为什么这不好?
TypeScript 的 ! 非空断言运算符会向类型系统断言某个表达式是非空的,也就是不是 null 或 undefined。使用断言向类型系统告知新信息,往往表明代码并非完全类型安全。通常更好的做法是组织程序逻辑,让 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 中添加。
