microsoft / microsoft/TypeScript

switch-true case-true narrowing not equivalent to default case.

Open
#59,133 0 comments 1 reaction 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.3k
Avg merge
1d 19h
Merged PRs (30d)
117

Description

🔎 Search Terms

"switch true" "switch-true" switch true narrowing. Most issues that turned up were from 2023 which I think precedes the release of the switch-true type narrowing feature?

🕗 Version & Regression Information
  • This is a gap
⏯ Playground Link

https://www.typescriptlang.org/play/?ts=5.6.0-dev.20240703&ssl=22&ssc=1&pln=12&pc=1#code/GYVwdgxgLglg9mABHA1gQwJ4AoZgA4hQBciAzlAE64DmAlIiQEQCCjAPowELuMDCjiAN4AoRGLIB3GFAgALRFkogApvRHiNiCGlLLEAejT6AdFGXkc+QrSKjN9isqggKSFowDcd+9t0GARiZmFrgEUDbe9uKOzq6IXJ6RGgAmysBoIAA2xElRMS5u-F4aAL7CZcKgkLAIiCCycLKWYSTkVGB0DPGsHNwc-EKRpFIy8ooUKmq5Yr56hkHmUM3WtlGa+XHuxVGzAQshVuGra9FOBfHc2z46ekrKxyeIG4WJpeXCQA

💻 Code
function uhoh(input: string) : "A"|"B"|"C" {
    switch (true) {
        case /a/.test(input):
            return "A";
        case /b/.test(input):
            return "B";
        case true: // <--- default: works fine here
            return "C";
    }
}
🙁 Actual behavior

Complains that the result of uhoh could be undefined.

🙂 Expected behavior

switch(true) { case true: } should behave like switch(true) { default: }, probably?

Additional information about the issue
image

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

Use the linked TypeScript Playground example as the starting repro. Trace how switch(true) handles the final case true versus default, then verify that the function no longer permits undefined while preserving the A/B/C results.

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
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.