microsoft / microsoft/TypeScript
Exhaustive switch case with returns can mark a finally block as unreachable
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
### 🔎 Search Terms
finally switch exhaustive unreachable
### 🕗 Version & Regression Information
This is the behavior in every version I tried ( doesn't typecheck pre 3.7 ), and I reviewed the FAQ for entries about unreachable code
### ⏯ Playground Link
https://www.typescriptlang.org/play/?#code/MYewdgzgLgBAhjAvDAFANwFwwIwwD4wBMAlEgHwwDeAUDDFAE4CeVtdMEA7gJZTAAWqNKRrt2wOBACmOLAylQArgzAw0bMROlE5C5avViAvmyMwAZtzBwANjZajx4CCBtSAdDZABzFAHIpAA9eP2JTahNqUEhYACMkISwwRQBbWKkGUkQKR0YHDQ4ePkF0EQK6LRlsXSUVNXKYABMpczhFGyga-XrjUwsrW3tWTWdXDy9fAOCoUPDI6OgYYAT0LFwCEnJh+mZtui5eASEysQrJKq66w1PKnRh5WoMCkzozS2s7fLFuc1RGRSkJxuozcnh8-iCITCvVeEWoUWcsEaK0wMGSaQyWRybDye0KhxKwjxZ201XueiuDWarXanXJjx67BeMDeA0+eJ+fwYAKBI0gYzBk0hM2hTLmQA
### 💻 Code
```ts
const c = (v: 1 | 2) => {
try {
switch (v) {
case 1: return v
case 2: return v
}
} finally {
if (true) {
console.log('exit')
}
}
}
```
### 🙁 Actual behavior
The contents of the `finally` blocked are marked as unreachable
### 🙂 Expected behavior
That they are reachable
### Additional information about the issue
While the example seems to include some confusing additions the replication apparently requires:
- The cases to be exhaustive
- No default case
- For the switch expression be typed as a literal union of some form
- An `if` statement to be in the `finally` block
I assume this is a chaotic mix of unreachable patterns upsetting flow analysis. I've also noticed that it you add an unreachable `return` statement after the `switch` then the contents of `finally` become reachable.
Contributor guide
Research direction
Start with the linked TypeScript Playground reproduction and compare the exhaustive literal-union switch inside try/finally with the listed variations: a default case or an unreachable return after the switch. Trace the flow analysis that marks the if statement in finally unreachable, then add coverage showing that the finally contents are reachable and verify the expected diagnostics.
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