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

Narrowing not works on discriminated unions when not using literal type as discriminator property #48522

Closed
k8w opened this issue Apr 2, 2022 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@k8w
Copy link

k8w commented Apr 2, 2022

Bug Report

πŸ”Ž Search Terms

Narrowing Union literal

πŸ•— Version & Regression Information

  • This changed between versions 4.0.5 and 4.6.2

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

// ------- EXPECTED -------
type Data1 = {
    type: 'string',
    a: string,
    b: string
} | {
    type: 'number',
    a: number,
    b: number
}

function test1(data: Data1) {
    if (data.type === 'string') {
        // Work as Expected: data.b is `string`
        data.b
    }
}

// ------- NOT EXPECTED -------

type Data2 = {
    type: string,
    a: string,
    b: string
} | {
    type: number,
    a: number,
    b: number
}

function test2(data: Data2) {
    if (typeof data.type === 'string') {
        // Expect: data.b is `string`
        // Actual: data.b is `string | number
        data.b
    }
}

πŸ™ Actual behavior

When discriminator property is not literal type in discriminated unions, type of Data2 is not narrowed as expected.

πŸ™‚ Expected behavior

Type of Data2 can be narrowed just like Data1

@jcalz
Copy link
Contributor

jcalz commented Apr 2, 2022

This changed between versions 4.0.5 and 4.6.2

Really? Looks the same for TS3.9.7

...which makes sense because this is working as intended. Discriminated unions in TS require the discriminant property to be of a literal/unit/singleton type in at least one of the members of the union. Neither string nor number are literal types, so the type property of Data2 is not a discriminant property.

@RyanCavanaugh
Copy link
Member

Most recently discussed at #48500

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