Can we disallow to use || on optional types by lint?

I want to disallow following code:

function(num: undefined|number) {
  return num || 10;
}

I want use ?? instead of ||.

  • Note that for num 0, nullish coalescing will return 0 while the or operator will return 10.

    – 




  • @JSONDerulo I believe that’s exactly the reason to prefer ?? – to avoid defaulting when using a falsy value.

    – 

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.

Leave a Comment