no-non-null-asserted-nullish-coalescing
Disallow non-null assertions in the left operand of a nullish coalescing operator.
在 ESLint 配置 中扩展"plugin:@typescript-eslint/strict"
可启用此规则。
此规则报告的一些问题可以通过编辑器 建议 手动修复。
??
空值合并运行时运算符允许在处理 null
或 undefined
时提供默认值。在空值合并运算符的左操作数中使用 !
非空断言类型运算符是多余的,很可能是程序员错误或对这两个运算符混淆的标志。
¥The ??
nullish coalescing runtime operator allows providing a default value when dealing with null
or undefined
.
Using a !
non-null assertion type operator in the left operand of a nullish coalescing operator is redundant, and likely a sign of programmer error or confusion over the two operators.
- Flat Config
- Legacy Config
export default tseslint.config({
rules: {
"@typescript-eslint/no-non-null-asserted-nullish-coalescing": "error"
}
});
module.exports = {
"rules": {
"@typescript-eslint/no-non-null-asserted-nullish-coalescing": "error"
}
};
在线运行试试这个规则 ↗
示例
¥Examples
- ❌ Incorrect
- ✅ Correct
foo! ?? bar;
foo.bazz! ?? bar;
foo!.bazz! ?? bar;
foo()! ?? bar;
let x!: string;
x! ?? '';
let x: string;
x = foo();
x! ?? '';
Open in Playgroundfoo ?? bar;
foo ?? bar!;
foo!.bazz ?? bar;
foo!.bazz ?? bar!;
foo() ?? bar;
// This is considered correct code because there's no way for the user to satisfy it.
let x: string;
x! ?? '';
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
'## 资源'