Skip to content

Omitting a property on a discriminated union type #54525

Closed
@Trekiros

Description

@Trekiros

Bug Report

When using Omit on a discriminated union type, the properties unique to each "branch" of the union type are lost.

🔎 Search Terms

Omit, union, discriminated union

🕗 Version & Regression Information

Tested on TypeScript 4.8.4 and on the nightly version (June 5th, 2023)

⏯ Playground Link

demo

Alternative demo (a different way to do discriminated unions, which is also affected)

💻 Code

type T = {
    name: string,
    type: 1,
    prop1: string,
} | {
    name: string,
    type: 2,
    prop2: string,
}

type T2 = Omit<T, 'name'>

🙁 Actual behavior

T2 is interpreted as such by TypeScript:

type T2 = {
    type: 1 | 2;
}

And the following object is seen as invalid:

const obj: T2 = {
    type: 2,
    prop2: 'abcd', // "prop2 does not exist on type T2"
}

🙂 Expected behavior

T2 should be interpreted like this instead:

type T2 = {
    type: 1;
    prop1: string;
} | {
    type: 2;
    prop2: string;
}

And the object described above should be seen as valid.

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions