Skip to content

Type narrowing not working in else statements #52272

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
mon-jai opened this issue Jan 17, 2023 · 4 comments
Closed

Type narrowing not working in else statements #52272

mon-jai opened this issue Jan 17, 2023 · 4 comments
Labels
Duplicate An existing issue was already created

Comments

@mon-jai
Copy link

mon-jai commented Jan 17, 2023

Bug Report

🔎 Search Terms

  • Narrowing
  • Else statements

🕗 Version & Regression Information

Playground link with relevant code

💻 Code

type Foo = (
    { name: "a" | "b"; isAorB: true }
    | { name: "c"; isC: true }
)

declare let foo: Foo

if (foo.name == "a" || foo.name == "b") {
    console.log(foo.isAorB)
} else {
    const name = foo.name // TypeScript recognize that foo.name == "c" and therefore, name == "c"
    console.log(foo.isC) // Error reported, yet we know that foo.isC == true
}

🙁 Actual behavior

TypeScript failed to recognize foo.isC.

🙂 Expected behavior

TypeScript recognize that foo.isC == true.

@MartinJohns
Copy link
Contributor

Duplicate of #43026.

@fatcerberus
Copy link

fatcerberus commented Jan 17, 2023

I’m not sure #43026 (comment) applies here since that involves a && in the initial if branch which can be decomposed into two separate (and insufficient) narrowing operations. The narrowings here should be atomic.

@MartinJohns
Copy link
Contributor

MartinJohns commented Jan 17, 2023

Fairly certain it does apply. When foo.name == "a" is falsy, there's nothing the type of foo can be narrowed to. Same applies for the other expression. And when you remove the union it works fine:

type Foo = (
    | { name: "a"; isAorB: true }
    | { name: "b"; isAorB: true }
    | { name: "c"; isC: true }
)

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Jan 18, 2023
@typescript-bot
Copy link
Collaborator

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

5 participants