Skip to main content

no-non-null-asserted-optional-chain

Disallow non-null assertions after an optional chain expression.

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

💡

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

如果对象是 nullundefined,则 ?. 可选链表达式提供 undefined。使用 ! 非空断言来断言 ?. 可选链表达式的结果不可空可能是错误的。

¥?. optional chain expressions provide undefined if an object is null or undefined. Using a ! non-null assertion to assert the result of an ?. optional chain expression is non-nullable is likely wrong.

大多数情况下,要么对象不可为空,并且不需要 ?. 进行属性查找,要么 ! 不正确并引入了类型安全漏洞。

¥Most of the time, either the object was not nullable and did not need the ?. for its property lookup, or the ! is incorrect and introducing a type safety hole.

eslint.config.mjs
export default tseslint.config({
rules: {
"@typescript-eslint/no-non-null-asserted-optional-chain": "error"
}
});

在线运行试试这个规则 ↗

示例

¥Examples

foo?.bar!;
foo?.bar()!;
Open in Playground

选项

该规则不可配置。

何时不使用它

¥When Not To Use It

如果你的项目的类型尚未完全描述某些值是否可以为空,例如你正在过渡到 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.

进一步阅读

¥Further Reading

'## 资源'