microsoft / microsoft/TypeScript

Type narrowing in one case statement does not propagate to the next case

Open
#56,361 10 comments 5 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Domain: check: Control Flow Help Wanted Possible Improvement
Dominant language
Go
Stars
111k
Forks
14.4k
Avg merge
1d 19h
Merged PRs (30d)
117

Description

🔎 Search Terms
  • Type narrowing
  • Switch statement
🕗 Version & Regression Information
  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about switch statements and type narrowing.
⏯ Playground Link

https://www.typescriptlang.org/play?ts=5.3.0-beta#code/GYVwdgxgLglg9mABMOcAUBDATgcwFyIDOUWMYOiAPouACYCmwZ9tAlIgN4BQivRA7jCgQAFojQkQ9dtz5zEEDIXqJsFALyaaYBkzAs8Pecagiscfon2WAolnNY0rANxcjxxctW4AdMWxQhADqQiJoAEQAHuGsBAD0cYj09nBYiAAqAMoAjAAcAAwALLkEAORqpYgwhIgADnCEhDAARgA2AJ6IpXSMzLSlPu7GfFj0UCBYSOEAguGuQ3K6GCCtUIbD8qPjk4jhAEJzQwC+XCdAA

💻 Code
function foo(arg: string | undefined) {
    switch (true) {
        case arg === undefined:
            throw new Error();

        case arg.startsWith("x"): // error TS18048: 'arg' is possibly 'undefined'.
            return "A";

        default:
            return "B";
    }
}
🙁 Actual behavior

error TS18048: 'arg' is possibly 'undefined'. in the second case.

🙂 Expected behavior

I expect the type to be narrowed to string in the second case statement.

Additional information about the issue

See also #56352. Ping @Andarist.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the linked TypeScript Playground reproduction and compare the related issue #56352. Trace how the switch cases are type-checked, then verify that the second case narrows arg to string without producing TS18048.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.