Skip to content

Type refinement doesn't work on destructured properties #36256

Closed
@StevenLangbroek

Description

@StevenLangbroek

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:

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions