Microsoft/TypeScript

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

Open

#59,133 创建于 2024年7月3日

在 GitHub 查看
 (0 评论) (1 反应) (0 负责人)TypeScript (6,726 fork)batch import
Domain: check: Control FlowHelp WantedPossible Improvement

仓库指标

Star
 (48,455 star)
PR 合并指标
 (平均合并 6天 17小时) (30 天内合并 9 个 PR)

描述

🔎 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

贡献者指南