54 lines
1.4 KiB
Plaintext
54 lines
1.4 KiB
Plaintext
== 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
|
|
|
|
[source,typescript,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
function either(x: number | undefined, y: number) {
|
|
return x || y;
|
|
}
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,typescript,diff-id=1,diff-type=compliant]
|
|
----
|
|
function either(x: number | undefined, y: number) {
|
|
return x ?? y;
|
|
}
|
|
----
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,typescript,diff-id=2,diff-type=noncompliant]
|
|
----
|
|
function either(x: number | undefined, y: number) {
|
|
return x !== undefined ? x : y;
|
|
}
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,typescript,diff-id=2,diff-type=compliant]
|
|
----
|
|
function either(x: number | undefined, y: number) {
|
|
return x ?? y;
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
|
|
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing[MDN Nullish coalescing]
|