I want to disallow following code:
function(num: undefined|number) {
return num || 10;
}
I want use ??
instead of ||
.
You can use the rule @typescript-eslint/prefer-nullish-coalescing:
This rule reports when you may consider replacing:
- An
||
operator with??
- An
||=
operator with??=
Also note that the rule documentation states:
CAUTION
This rule will not work as expected if
strictNullChecks
is not enabled.
To enable it add "@typescript-eslint/prefer-nullish-coalescing": "error"
to the rules in the linter configuration.
Read the documentation page for additional configuration options for the rule.
typescript-eslint.io/rules/prefer-nullish-coalescing
Note that for num
0
, nullish coalescing will return0
while the or operator will return10
.@JSONDerulo I believe that’s exactly the reason to prefer
??
– to avoid defaulting when using a falsy value.