no-non-null-asserted-nullish-coalescing
Disallow non-null assertions in the left operand of a nullish coalescing operator.
Extending "plugin:@typescript-eslint/strict"
in an ESLint configuration enables this rule.
Some problems reported by this rule are manually fixable by editor suggestions.
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"
}
};
Try this rule in the playground ↗
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 PlaygroundOptions
This rule is not configurable.
When Not To Use It
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.