no-extra-non-null-assertion
Disallow extra non-null assertions.
✅
在 ESLint 配置 中扩展"plugin:@typescript-eslint/recommended"
可启用此规则。
🔧
此规则报告的一些问题可通过 --fix
ESLint 命令行选项自动修复。
TypeScript 中的 !
非空断言运算符用于断言值的类型不包括 null
或 undefined
。
对单个值多次使用该运算符不会产生任何效果。
英:The !
non-null assertion operator in TypeScript is used to assert that a value's type does not include null
or undefined
.
Using the operator any more than once on a single value does nothing.
.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/no-extra-non-null-assertion": "error"
}
};
示例
- ❌ 不正确
- ✅ 正确
const foo: { bar: number } | null = null;
const bar = foo!!!.bar;
Open in Playgroundfunction foo(bar: number | undefined) {
const bar: number = bar!!!;
}
Open in Playgroundfunction foo(bar?: { n: number }) {
return bar!?.n;
}
Open in Playgroundconst foo: { bar: number } | null = null;
const bar = foo!.bar;
Open in Playgroundfunction foo(bar: number | undefined) {
const bar: number = bar!;
}
Open in Playgroundfunction foo(bar?: { n: number }) {
return bar?.n;
}
Open in Playground选项
该规则不可配置。