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.
module.exports = {
"rules": {
"@typescript-eslint/no-non-null-asserted-nullish-coalescing": "error"
}
};
示例
- ❌ 不正确
- ✅ 正确
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何时不使用它
如果你的项目类型尚未完全描述某些值是否可以为空(例如,如果你要转换到 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.
进一步阅读
选项
该规则不可配置。