S6606 “Nullish coalescing should be preferred” should not fire on object-only nullable types

  • What language is this for? TypeScript

  • Which rule? typescript:S6606

  • Why do you believe it’s a false-positive/false-negative?

In this code:

function foo (bar: { baz: number } | null) {
  return bar || 'fallback';
}

the operator || is equivalent to ?? because there are no non-nullish primitive types in the type of bar, and thus no possible values for which || differs from ??.

We prefer the operator || in these cases because ?? transpiles to verbose gunk.

  • Are you using …

I am using SonarCloud.

  • How can we reproduce the problem? Give us a self-contained snippet of code (formatted text, no screenshots)
function foo (bar: { baz: number } | null) {
  return bar || 'fallback';
}
1 Like

Hello @gthb,

thanks for reporting this. Indeed you are correct and object-only alternatives cannot be falsy. We already had a ticket considering an improvement for the rule. I added your feedback to also consider objects.

Thanks!
Victor

1 Like