I have been using discriminated unions (DU) more frequently and have come to love them. I do however have one issue I can't seem to get past. If you inline a boolean check for the DU, you can rely on TypeScript (TS) to automatically infer the type for you. However, if you extract the boolean check, TS can no longer narrow to the specific subtype of the DU. I’m aware of type guards, but I’d like to know why the compiler doesn’t support extracted online checks, specifically.
Is this a known limitation? Should I file a bug/feature request?
Example here (w/ 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);
}
};