Skip to content

Type narrowing not working with multiple adjacent case statementsΒ #56352

Closed
@johan13

Description

@johan13

πŸ”Ž Search Terms

"switch", "type narrowing"

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about narrowing and switch statements

⏯ Playground Link

https://www.typescriptlang.org/play?#code/GYVwdgxgLglg9mABMOcAUBDATgcwFyIDOUWMYOiAPouACYCmwZ9tAlIgN4BQiviMwRGgCE2HOygALLHADuiMPXkBRLDKxpWAbi48+hWTCgRJQkiHrtufG4ggZC9RGIB0UOAFUADl-pYAwg70mogAvOGIAEQAgpEEAPTxiADyANJ6trZY9FAgWEgxkToZtvaOzrhunj5+gY4h4aFRAEJxiImIfuqIACoAygCMABwADAAsQwQA5GJT-ISIXnCEhDAARgA2AJ6IU3SMzLRTLiU2ZU6u7t6+AUENEZH+bR1dcFi9g6MT07Pzi8urTY7PZgBhMRRHE6ZXjnCo4KrXWp3diNKIAEWeSTSp2h2Vy+RaABpEP5EG9EBidDYAL66Gx4vIFABycCgiGixOaxNJ5MpXFpQA

πŸ’» Code

function foo(arg: string | undefined) {
    if (!arg) throw new Error();

    switch (true) {
        case arg.toUpperCase() === "A": // OK
            return "A";

        case arg.toUpperCase() === "B": // error TS18048: 'arg' is possibly 'undefined'.
        case arg.toUpperCase() === "C": // error TS18048: 'arg' is possibly 'undefined'.
        case arg.toUpperCase() === "D": // OK
            return "B, C or D";
    }

    return "Not A, B, C or D";
}

πŸ™ Actual behavior

In two of the four case statements, the arg variable has the type string | undefined instead of string.

πŸ™‚ Expected behavior

I would expect the arg variable to have the same type in all four case statements.

Additional information about the issue

No response

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFix AvailableA PR has been opened for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions