typescript:S3801 false positive when a switch handles all variants

  • What language is this for?
    TypeScript

  • Which rule?
    typescript:S3801 - Functions should use “return” consistently

  • Why do you believe it’s a false-positive/false-negative?
    False positive, see the code below.
    Tested with TypeScript 5.0.4.

  • Are you using
    SonarQube - Enterprise Edition Version 9.9.1 (build 69595)

  • How can we reproduce the problem? Give us a self-contained snippet of code (formatted text, no screenshots)

export type Variant = "A" | "B" | "C";

// SQ: Refactor this function to use "return" consistently.
// But the default case is not needed here, since TS compiler already ensures that the switch returns something for every input variant.
export function getVariantNumber(variant: Variant): number {
    switch (variant) {
        case "A":
            return 1;
        case "B":
            return 2;
        case "C":
            return 3;
    }
}

Hello Jan,

Welcome to Sonar’s community, sorry for the long delay in answering you, and many thanks for the highly appreciated feedback!

As you rightfully pointed out, the code snippet you shared does indeed raise a false positive. I created this ticket to keep track of the problem and address it soon hopefully.

Best,
Yassin

Hi, I also noticed this a couple of times now and it always requires a manual click on false positive… Seems this is not fixed yet?

Jira Issue is JS-90

Last update there is from Oct 2024 that decreased the priority from urgent to normal :frowning:

Is there a way to vote for issues? :stuck_out_tongue:

Anything that someone could provide as help for fixing this?

Hi Peter,

Thanks for linking the updated issue.

Posting a message as you did is the right way to upvote an issue.

This issue is really annoying. Is there anything one could help to fix it?

I noticed that there is now a second issue created in Jira: JS-505 next to JS-90, which could be marked as dup by someone with write access to Jira :slight_smile:

In cases where a function should handle all cases of e.g. a enum within a switch, we actually prefer to have no default return, to ensure in case the enum might be modified (which might come form an external API) we get a a compile error. So at the moment, I quite often mark those cases as false positives.

Hi @ptandler,

thanks for spotting the duplicate, I removed JS-505

As for the fix, we should have a rules hardening soon. Sorry for the delay

Cheers

Hi @ptandler and @jpikl-prgs,

Hopefully this will addressed soon as we have PR ready - JS-90 Fix S3801: Handle exhaustive switch statements over union types by zglicz · Pull Request #6146 · SonarSource/SonarJS · GitHub

Kind regards,

Michal