microsoft / microsoft/TypeScript
TypeScript can't infer correct type from while loop if while condition is given a promise
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.4k
- Avg merge
- 1d 19h
- Merged PRs (30d)
- 117
Description
🔎 Search Terms
promise in while loop condition
🕗 Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about Bugs that aren't bugs
⏯ Playground Link
💻 Code
function sleep(ms: number): Promise<true> {
return new Promise<true>(a => setTimeout(() => a(true), ms))
}
async function example1(): Promise<string> {
let value: string | undefined
while (true) {
await sleep(5000)
value = '5'
break
}
return value
}
async function example2(): Promise<string> {
let value: string | undefined
while (await sleep(5000)) {
value = '5'
break
}
return value
}
🙁 Actual behavior
In example2, TypeScript can't infer the type of value and that it should be now a string and not undefined simply because the Promise that returns true in the while loop has been moved to the while condition instead of the body of the while loop.
🙂 Expected behavior
The expected behaviour should be that TypeScript should be able to infer that it is still a string at the return statement just like in example1
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 and compare control-flow analysis for example1 and example2, focusing on the awaited promise in the while condition. Done means the second example is accepted as returning Promise without weakening the reported types or changing the example's intended behavior.
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
- 38/100