typescript:S6606 incorrect suggestion - mixes up null and undefined

  • What language is this for? Javascript/Typescript

  • Which rule? typescript:S6606

  • Why do you believe it’s a false-positive/false-negative? Its suggestion changes the program flow.

  • Are you using

    • SonarQube for IDE - which IDE/version? 10.22.0.81244
  • How can we reproduce the problem? Give us a self-contained snippet of code (formatted text, no screenshots)

Example code:

let x = null;
if (x === undefined) {
  x = 3;
}
// the result will be null

typescript:S6606 suggest to replace it with code:

let x = null;
x ??= 3;
// the result will be 3, not null, as for ??= operator 
// both null and undefined are treated as falsy.
1 Like

I agree that this is a FP, as following the suggestion of the issue breaks the code.

@dominioon - I tried running unit tests with this snippet and it doesn’t raise an issue for me. Perhaps this is simplified to a point it doesn’t raise?

Please note, we base this rule off of typescript-eslint rule implementation - prefer-nullish-coalescing | typescript-eslint . They have made a few changes to it in the recent releases and we will have an update to SonarQube IDE soon.

Kind regards,
Michal

You are right, it was simplified. I Played around with the actual code I have and understood that I mixed up 2 methods in my code with different signatures, and actually there is nothing wrong with the S6606 rule. I’m very sorry for causing confusion :flushed_face:.
The method that I had actually does NOT allow null as input. And if it does, then the S6606 does not fire up:

function foo(x?: number) {
  if (x === undefined) { // Sonar suggests to use ??=, as null's are not allowed
    x = 3;
  }
  console.log(x);
}
function bar(y?: number | null) {
  if (y === undefined) { // no Sonar warnings, as nulls are also allowed
    y = 3;
  }
  console.log(y);
}
2 Likes