Why is this an issue?
The nullish coalescing operator ??
allows providing a default value when dealing with null
or undefined
. It
only coalesces when the original value is null
or undefined
. Therefore, it is safer and shorter than relying upon chaining
logical ||
expressions or testing against null
or undefined
explicitly.
This rule reports when disjunctions (||
) and conditionals (?
) can be safely replaced with coalescing
(??
).
The TSConfig needs to set strictNullChecks
to true
for the rule to work properly.
How to fix it
Rewrite the logical expression ||
using ??
on the unchecked operands.
Code examples
Noncompliant code example
function either(x: number | undefined, y: number) {
return x || y;
}
Compliant solution
function either(x: number | undefined, y: number) {
return x ?? y;
}
Noncompliant code example
function either(x: number | undefined, y: number) {
return x !== undefined ? x : y;
}
Compliant solution
function either(x: number | undefined, y: number) {
return x ?? y;
}
Resources