Recently, I've been using discriminated unions (DU) more frequently and have really started to appreciate their benefits. However, I've encountered a challenge that I can't seem to resolve. When I include a boolean check inline for the DU, TypeScript (TS) can automatically infer the type for me. But when I extract the boolean check, TS struggles to narrow down to the specific subtype of the DU. I know about type guards, but I'm curious as to why the compiler doesn't support extracted online checks specifically.
Is this a well-known limitation in TypeScript? Should I consider submitting a bug/feature request for this issue?
For illustration, you can refer to the example below (with TypeScript Playground Link):
type A = { type: "A"; foo: number };
type B = { type: "B"; bar: string };
type DU = A | B;
const checkIt = (it: DU) => {
const extractedCheck = it.type === "A";
if (extractedCheck) {
// it does not get narrowed
console.log(it.foo); // Error: Property 'foo' does not exist on type 'DU'.
}
if (it.type === "A") {
// but this is fine
console.log(it.foo);
}
};