Microsoft/TypeScript

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

Open

#56,361 创建于 2023年11月10日

在 GitHub 查看
 (10 评论) (5 反应) (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

  • 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.

贡献者指南