Skip to content

Discriminated Unions Incompatible with Intersection Types #11989

Closed

Description

TypeScript Version: 2.0.3 AND nightly (2.1.0-dev.20161102)

Code

interface Foo {
    kind: 'foo';
    a: number;
}

interface Bar {
    kind: 'bar';
    b: string;
}

function test(x: Bar|Foo) {
    if (x.kind === 'foo') {
        console.log(x.a); // Valid, as expected
    }
}

interface Qux {
    c: boolean;
}

function test2(x: (Bar|Foo)&Qux) {
    if (x.kind === 'foo') {
        // Type of x should be Foo&Qux now, but is still (Bar|Foo)&Qux
        console.log(x.a); // Error
    }
}

Expected behavior:
In test2(), the discriminated union check should narrow the type down to (Foo)&Qux, letting you access property a, since a is guaranteed to be there if x.type === 'foo'.

Actual behavior:
No type narrowing is done whatsoever. The type of x remains (Foo|Bar)&Qux.

Activity

  1. ahejlsberg commented on Nov 2, 2016

    @ahejlsberg
    Member

    This looks like a duplicate of #9919, which was fixed in #11717. I can compile your example with no error in the nightly build and x is narrowed to Foo & Qux as expected. Can you reconfirm that there's an issue in the nightly?

  2. MikeyBurkman commented on Nov 2, 2016

    @MikeyBurkman
    Author

    Anders Hejlsberg (@ahejlsberg) Ah I stand corrected. tsc on the command line does indeed work, it's just that it's still be reported as an error in VS Code. Not sure whether to report that as a different issue or not.

    Also I do have another, different but related bug that is reproduceable on the command line on the nightly build :)

  3. locked and limited conversation to collaborators on Jun 19, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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