Microsoft/TypeScript

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

Open

#56 361 ouverte le 10 nov. 2023

Voir sur GitHub
 (10 commentaires) (5 réactions) (0 assignés)TypeScript (6 726 forks)batch import
Domain: check: Control FlowHelp WantedPossible Improvement

Métriques du dépôt

Stars
 (48 455 stars)
Métriques de merge PR
 (Merge moyen 6j 17h) (9 PRs mergées en 30 j)

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.

Guide contributeur