microsoft / microsoft/TypeScript
Type narrowing in one case statement does not propagate to the next case
Open
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
💻 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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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