Skip to content

aliasing discriminated union tag breaks case analysis #10830

Closed
@Swatinem

Description

@Swatinem

TypeScript Version: 2.1.0-dev.20160909

Code

type A = {t: "a", a: string};
type B = {t: "b", b: string};
type U = A | B;

const a: U = {t: "a", a: "a"} as U;

if (a.t === "b") {
    a.b; // works as expected
}

const {t} = a;
if (t === "b") {
    a.b; // error TS2339: Property 'b' does not exist on type 'U'.
}

Expected behavior:

The type of a.t should correctly transfer to t when assigning or using destructuring. t should be usable as discriminant.

Actual behavior:

The type of t is widened from "a" | "b" to string and therefore can not be used as discriminant any more.

As the same happens also for flow (See facebook/flow#2409), it may be my thinking that is a little bit off. But I think that the case should be valid. The programmer should not be forced to repeat base. all over, that’s what variables are for.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Fix AvailableA PR has been opened for this issueSuggestionAn idea for TypeScriptToo ComplexAn issue which adding support for may be too complex for the value it adds

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions