Skip to content
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

Adding boolean type assertion changes type narrowing #60190

Closed
jauwesome opened this issue Oct 10, 2024 · 4 comments
Closed

Adding boolean type assertion changes type narrowing #60190

jauwesome opened this issue Oct 10, 2024 · 4 comments
Labels
Not a Defect This behavior is one of several equally-correct options

Comments

@jauwesome
Copy link

πŸ”Ž Search Terms

Type Narrowing
Boolean
Undefined

πŸ•— Version & Regression Information

Version: 5.6.3
Regression: Unknown

⏯ Playground Link

https://www.typescriptlang.org/play/?noUnusedLocals=true&noUnusedParameters=true#code/GYVwdgxgLglg9mABFApgZygeTCgFMOOALkQwCcYwBzRAH0XABMVhKVGBKRAbwChEBiCAgzIAFpRoBeRAEJZBOAG5+gmMFxQJ1Ln0H7EZFFBBkkigHQQxAQzIBBKLgAMHFfoC+qgUZNnEAORMLGyMAbxevKCQsAjI6FAAKgDucPiEJOSSdAxgzKw4nDzeQiJQ4pIkAEaEADYoNkgy8oruahpakrol+r6m5oRWtg5Orm0CXr3G-YHBBezhHkA

πŸ’» Code

function testOne(foo: string | undefined) {
    const thing = !!foo;
    if(thing) {
        // Foo type is String
        return foo.charAt(0);
    }
    return 'undefined'
}

function testTwo(foo: string | undefined) {
    const thing: boolean = !!foo;
    if(thing) {
         // Foo type is string | undefined
        return foo.charAt(0);
    }
    return 'undefined'
}

πŸ™ Actual behavior

foo is typed as string | undefined if thing has explicit type of boolean

πŸ™‚ Expected behavior

foo should be typed as string if thing has type of boolean just like if thing's type is inferred

Additional information about the issue

No response

@jauwesome jauwesome changed the title Adding boolean type assertion changes type narrowing for undefined Adding boolean type assertion changes type narrowing Oct 10, 2024
@RyanCavanaugh RyanCavanaugh added the Not a Defect This behavior is one of several equally-correct options label Oct 10, 2024
@RyanCavanaugh
Copy link
Member

This was an intentional boundary in #44730

@jauwesome
Copy link
Author

@RyanCavanaugh Thanks for the quick response! Is there a specific reason why this choice was made? I don't see that listed. Regardless we can close the ticket.

@RyanCavanaugh
Copy link
Member

IIRC it's possible to get into a type resolution circularity with this inference in a way that wouldn't really be solvable, so you need some "out" in cases where you're not using it for narrowing purposes

@jauwesome
Copy link
Author

Good to know! That makes sense. Thanks again for your help!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Not a Defect This behavior is one of several equally-correct options
Projects
None yet
Development

No branches or pull requests

2 participants