While experimenting with generic type unions, I discovered a behavior of typescript that causes runtime errors despite the compiler's clear ability to detect wrong types and report them at build time.
here is the code snippet which will always fail
type MyVar<A, B> = {
a: A;
b: B;
};
const make = (): MyVar<number, string> => {
let a = 0;
let b = "str";
return Math.random() > 0.5 ? { a } as MyVar<number, never>: { b } as MyVar<never, string>;
}
let inst = make();
console.log(inst.a.toFixed());
console.log(inst.b.concat("1"));
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.