Skip to content

Type refinement doesn't work on destructured properties #36256

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
StevenLangbroek opened this issue Jan 17, 2020 · 2 comments
Closed

Type refinement doesn't work on destructured properties #36256

StevenLangbroek opened this issue Jan 17, 2020 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@StevenLangbroek
Copy link

TypeScript Version: 3.7 (tried nightly too)

Search Terms:

  • refinement destructuring
  • refinement destructure
  • refinement destructured property
  • refinement union destructured

Code

type Result = {
    __typename: 'AuthError'
} | {
    __typename: 'OtherError'
} | {
    __typename: 'User';
    firstName: string;
    lastName: string;
}

const getResult = (): Promise<Result> => fetch('some/url').then(res => res.json());

getResult().then(result => {
    const { __typename } = result;

    if (__typename === 'AuthError') {
        return;
    }

    if (__typename === 'OtherError') {
        return;
    }

    // result isn't refined into `__typename: User` here:
    console.log(result.firstName);
})

Expected behavior:

I'd expected this to be refined regardless of whether testing the destructured discriminator or accessing it through the argument.

Actual behavior:

When destructuring the type is not refined.

Playground Link:

Playground

Related Issues:

@ajafff
Copy link
Contributor

ajafff commented Jan 17, 2020

searching for "refinement destructuring" brought up issue #35283 which is basically the same.
TypeScript cannot narrow a variable based on another variable's refinement.

@DanielRosenwasser DanielRosenwasser added the Duplicate An existing issue was already created label Jan 18, 2020
@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