Closed
Description
TypeScript Version: 3.0.1 and 3.1.0-dev.20180829
Search Terms:
Code
type A = {
type: "A";
aprop: number;
};
type B = {
type: "B";
bprop: number;
};
function aFunc() {
return { type: "A", aprop: 2 }
};
function bFunc() {
return { type: "B", bprop: 2 }
};
function aFuncTyped(): A {
return { type: "A", aprop: 2 }
};
function bFuncTyped(): B {
return { type: "B", bprop: 2 }
};
// 1. Discriminated with ReturnType of explicitely typed functions: all good.
let x2: ReturnType<typeof aFuncTyped> | ReturnType<typeof bFuncTyped>;
if (x2.type === "A") {
x2.aprop;
}
if (x2.type === "B") {
x2.bprop;
}
// 2. Discriminated with ReturnType of implicitely typed functions: errors.
let x3: ReturnType<typeof aFunc> | ReturnType<typeof bFunc>;
if (x3.type === "A") {
// Property 'aprop' does not exist on type '{ type: string; aprop: number; } | { type: string; bprop: number; }'.
// Property 'aprop' does not exist on type '{ type: string; bprop: number; }'.
x3.aprop;
}
if (x3.type === "B") {
// Property 'bprop' does not exist on type '{ type: string; aprop: number; } | { type: string; bprop: number; }'.
// Property 'bprop' does not exist on type '{ type: string; aprop: number; }'.
x3.bprop;
}
Expected behavior:
Should not fail to compile.
ReturnType
infers correctly the type of afunc()
and bfunc()
, however it fails to apply the correct discriminate in the if
statements.
Actual behavior:
Fails to compile with the error messages indicated in code.