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

User-defined type guards cannot narrow discriminated union types #49782

Closed
yenshih opened this issue Jul 5, 2022 · 2 comments
Closed

User-defined type guards cannot narrow discriminated union types #49782

yenshih opened this issue Jul 5, 2022 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@yenshih
Copy link

yenshih commented Jul 5, 2022

Bug Report

πŸ”Ž Search Terms

  • user-defined type guards

  • narrowing

  • discriminated union

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about narrowing

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

type FooBar<T = 'foo' | 'bar'> = T extends string ? { type: T; value: Capitalize<T> } : never;

declare const fooBar: FooBar;

const isFoo = (type: 'foo' | 'bar'): type is 'foo' => type === 'foo';

if (fooBar.type === 'foo') {
    // 'Foo'
    fooBar.value
}

if (isFoo(fooBar.type)) {
    // 'Foo' | 'Bar' ???
    fooBar.value
}

πŸ™ Actual behavior

typeof fooBar.value in the second if block is 'Foo' | 'Bar'

πŸ™‚ Expected behavior

typeof fooBar.value in the second if block should be 'Foo' instead of 'Foo' | 'Bar'

@MartinJohns
Copy link
Contributor

MartinJohns commented Jul 5, 2022

Duplicate of #42384.

You can work around this issue by narrowing the object, not the property:

const isFoo = (val: FooBar): val is FooBar<'foo'> => val.type === 'foo';

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Jul 5, 2022
@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

4 participants