Skip to content

Incorrect type narrowing with async/await #62908

@RareScrap

Description

@RareScrap

🔎 Search Terms

"type narrowing", "async", "await", "promise"

🕗 Version & Regression Information

  • This changed between versions ______ and _______
  • This changed in commit or PR _______
  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about all relevant to async/await and Promises
  • I was unable to test this on prior versions because _______

⏯ Playground Link

https://www.typescriptlang.org/play/?target=99&jsx=0#code/IYZwngdgxgBAZgV2gFwJYHsI2QUxMgCgEoAuGABQCd0BbVEHAHgDd1UATAPhgG8AoGIJgAbHMnipK+AEp50w5jnZVa9HABUwABxxkARAEY9MAD4w9AJmNmk7HHFQQlMALwxb9x0oFComfDAA2lrUdAwGKmE4AMpiyKLssiAIwsgANDAhqgwWkWqxyPFKSSnIALquMMAA7sCo4nkMAHTAwsIFRewEgT5CQo04TZRyCjgEetG0OANGRE3IABY4EAT1rtz8fVtCDlLISfKKyqFqmjowAPwXboZ6vdtCw8gIlFj1930AvkRpH-0nzWGIEOYwmUwGVjmi2Wq3ELg2f22uxkIyOAzOOEu13MVkRWyeLzeyDx33uZSIfHuAHoqTB1EtMtQAEaiGgwejYBbAcR+GhaVCiSgwZLDTmY5DaTEczDCMDuCB2BxOdgwaoLVBQBbskCq6gQADm9z8EGBoiawnQ+oIAANkftUUp0ZKXAASHh2g6jY7ZDSSz7Wil9Y2mwYWq1ZKIRAExOIJEqpQO+fzyUOWggRtS5aMdON4UoUz6U3D4YhAA

💻 Code

async function test(): Promise<void> {
    let firstResolvedPromiseType: "1" | "2" | undefined = undefined
    const [promise1PromiseSettledResult, promise2PromiseSettledResult] = await Promise.allSettled([
        Promise.resolve("SomePromise1").then(it => {
            firstResolvedPromiseType ??= "1"
            return it
        }),
        Promise.resolve("SomePromise2").then(it => {
            firstResolvedPromiseType ??= "2"
            return it
        })
    ])

    // The problem is that compiler sure the type is only undefined which is wrong
    console.log(`firstResolvedPromiseType=${firstResolvedPromiseType}`)
    console.log(promise1PromiseSettledResult)
    console.log(promise2PromiseSettledResult)
}

test()

🙁 Actual behavior

Compiler is absolutely sure that the only possible value of firstResolvedPromiseType is undefined which is wrong:

Image

🙂 Expected behavior

Compiler correctly determine the type of firstResolvedPromiseType as "1" | "2" | undefined

Additional information about the issue

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions