typescript:S1121 Should ignore chained assignments

  • versions used: TypeScript analyzer on SonarCloud (as of July 1, 2020)
  • minimal code sample to reproduce, based on the example for Java:
declare let i: number;

let j = i = i || 1;
const k = (j += 1);

Chained assignments should be ignored, similarly to: https://rules.sonarsource.com/java/tag/misra/RSPEC-1121
https://rules.sonarsource.com/csharp/RSPEC-1121

Instead we get:

hello @xemlock,

thanks for the suggestion, however can you provide some backing for it? I am not convinced that this is generally useful pattern to follow, see for example AirBnB JS guide . I tend to think that putting the assignments as separate statements would improve clarity in this case.

Using chained assignment in declarations is also dangerous because you may accidentally create global variables, e.g. in let x = y = 1 , if y is not declared, it will be hoisted as global.

1 Like

Using chained assignment in declarations is also dangerous because you may accidentally create global variables

Ok, fair point. It’s much harder to fell for this in TypeScript, because you’ll get an instant feedback from the compiler about the undefined variable, but it’s possible nonetheless.

Chained assignments are kind of standard and convenient (more performant as well?), but I agree that their use (especially by less experienced developers) may lead to unwanted side effects.

Anyway, I’m okay with your explanations. It would be nice however if you (or whoever else capable doing it) could extend the description of the rule in Sonar with what you’ve written in your reply, especially the part about unintentional global variables.

Thanks.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.