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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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