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 fo
Currently nope as mentioned by @jcalz, however there's a minimal workaround that you can always apply to overcome this problem.
The trick is to make extractCheck
a function that returns type predicate.
(Refer https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards)
The following is a working example:
type A = { type: "A"; foo: number };
type B = { type: "B"; bar: string };
type DU = A | B;
const checkIt = (it: DU) => {
// Make `extractCheck` a function
const extractedCheck = (it: DU): it is A => it.type === "A";
if (extractedCheck(it)) {
console.log(it.foo); // No error
}
};