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

Type narrowing of union types by type predicate narrows to only first branch of union #44754

Closed
Pajn opened this issue Jun 26, 2021 · 2 comments Β· Fixed by #49625
Closed

Type narrowing of union types by type predicate narrows to only first branch of union #44754

Pajn opened this issue Jun 26, 2021 · 2 comments Β· Fixed by #49625
Labels
Duplicate An existing issue was already created

Comments

@Pajn
Copy link

Pajn commented Jun 26, 2021

Bug Report

πŸ”Ž Search Terms

union type, type predicate

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about "Common Bugs That Aren't Bugs"

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

type Foo = {kind: 'foo'}
interface Bar<T = Any> {kind: 'bar', value: T}
type Baz = {kind: 'baz'}
type Any = Foo | Bar | Baz

function isFoobar(value: unknown): value is Foo | Bar<Foo> {
    return typeof value === 'object' && ((value as any)?.kind === 'foo' || (value as any)?.kind === 'bar')
}

let value = {kind: 'baz'} as Any

if (isFoobar(value)) {
    let a = value.kind === 'foo'
    ? value.kind
    : value.value.kind
}

πŸ™ Actual behavior & πŸ™‚ Expected behavior

isFoobar narrows the type to only Foo but should narrow it to the specified Foo | Bar<Foo>. It seems to be related to the combination of the generic parameter and the circularity because I can not find a way to simplify it further.

@andrewbranch
Copy link
Member

Duplicate of #31156

@andrewbranch andrewbranch marked this as a duplicate of #31156 Jun 28, 2021
@andrewbranch andrewbranch added the Duplicate An existing issue was already created label Jun 28, 2021
@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
3 participants