Closed
Description
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.