Skip to content

“This condition will always return true” is, in fact, false #61531

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
martynchamberlin opened this issue Apr 4, 2025 · 2 comments
Closed

Comments

@martynchamberlin
Copy link

🔎 Search Terms

This condition will always return true since this 'Promise' is always defined.

🕗 Version & Regression Information

⏯ Playground Link

https://www.typescriptlang.org/play/?ts=4.3.5#code/DYUwLgBATiDOCuwwC4IAUoHsC2BLWIAPAIYB2AngHwQA+EpiwEAvPSAO7pZ4EAUMsTMABuIFtQDeAKAiyIBMABVc2EJnhhevAJTiI0uYehxEkVg2DAZR2QKGjeF4NuuyAvgBoIARgAMvlzcXKWJYclIAYwgAM3hIsFxMUmg4nX1XCFxoiH4TJF0DGwhidmJcSAFTDIzDLJzK-PSiowikwVAAOmBMAHNeAHIwKA0AC3J+l2a3CBBgAibmuVbSdpAu3oHo4jmQccmitwzDw6lh0h0gA

💻 Code

let result: Promise<any> | null = new Promise(resolve => {
    setTimeout(() => {
        result = null
        resolve(null)
    }, 100)
})

async function run() {
    if (result) {
        await result
    
        if (result) {
            console.log('truthy')
        } else {
            console.log('falsey')
        }
    }
}

run()

🙁 Actual behavior

TS throws an error on line 12 which it shouldn't be throwing:

This condition will always return true since this 'Promise' is always defined.(2801)
input.tsx(12, 13): Did you forget to use 'await'?

🙂 Expected behavior

TS should not throw this error on line 12:

This condition will always return true since this 'Promise' is always defined.

It's making an opinion about a value at runtime that it doesn't have adequate context to adjudicate.

Additional information about the issue

That broader scope conditional on line 9 is narrowing the result type down from Promise<any> | null to Promise<any>, but then the check on line 12 is failing to account for the fact that result could get its value reassigned in virtue of the await on line 10. That await should cause the result type to expand back to the original Promise<any> | null, and make subsequent truthy checks allowable without type errors.

@MartinJohns
Copy link
Contributor

@martynchamberlin
Copy link
Author

Ah, ok. Thanks, will close as duplicate. I saw that template but didn't initially think it fit. Reading it in full though I see what you're saying. Closing this as duplicate. Sorry for your time! Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants