Skip to main content

no-non-null-assertion

Disallow non-null assertions using the ! postfix operator.

🔒

ESLint 配置 中扩展"plugin:@typescript-eslint/strict" 可启用此规则。

💡

此规则报告的一些问题可以通过编辑器 建议 手动修复。


TypeScript 的 ! 非空断言运算符向类型系统断言表达式不可为空,如 not nullundefined 所示。 使用断言告诉类型系统新信息通常表明代码不完全类型安全。 通常最好构建程序逻辑,以便 TypeScript 理解值何时可以为空。

英:TypeScript's ! non-null assertion operator asserts to the type system that an expression is non-nullable, as in not null or undefined. Using assertions to tell the type system new information is often a sign that code is not fully type-safe. It's generally better to structure program logic so that TypeScript understands when values may be nullable.

.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/no-non-null-assertion": "error"
}
};
在线运行试试这个规则 ↗

示例

interface Example {
property?: string;
}

declare const example: Example;
const includesBaz = example.property!.includes('baz');
Open in Playground

何时不使用它

如果你的项目类型尚未完全描述某些值是否可以为空(例如,如果你要转换到 strictNullChecks),则此规则可能会创建许多错误报告。 你可以考虑在这些特定情况下使用 ESLint 禁用注释,而不是完全禁用此规则。

英:If your project's types don't yet fully describe whether certain values may be nullable, such as if you're transitioning to strictNullChecks, this rule might create many false reports. You might consider using ESLint disable comments for those specific situations instead of completely disabling this rule.

选项

该规则不可配置。

资源