no-non-null-assertion
Disallow non-null assertions using the
!
postfix operator.
在 ESLint 配置 中扩展"plugin:@typescript-eslint/strict"
可启用此规则。
此规则报告的一些问题可以通过编辑器 建议 手动修复。
TypeScript 的 !
非空断言运算符向类型系统断言表达式不可为空,如 not null
或 undefined
。使用断言告诉类型系统新信息通常表明代码不完全类型安全。通常最好构建程序逻辑,以便 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.
- Flat Config
- Legacy Config
export default tseslint.config({
rules: {
"@typescript-eslint/no-non-null-assertion": "error"
}
});
module.exports = {
"rules": {
"@typescript-eslint/no-non-null-assertion": "error"
}
};
在线运行试试这个规则 ↗
示例
¥Examples
- ❌ Incorrect
- ✅ Correct
interface Example {
property?: string;
}
declare const example: Example;
const includesBaz = example.property!.includes('baz');
Open in Playgroundinterface Example {
property?: string;
}
declare const example: Example;
const includesBaz = example.property?.includes('baz') ?? false;
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.
'## 资源'