Skip to content

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

Closed
@k8w

Description

@k8w

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

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