day-1-type-narrowing.ts - generic version.
ahamed opened this issue · comments
Sajeeb Ahamed commented
type Rectangle = {
width: number;
height: number;
};
type Circle = {
radius: number;
};
const pi = 3.1415_9265_3589; // typescript infer the type
const getAreaGeneric = <T extends Rectangle | Circle>(shape: T) => {
if ('radius' in shape) {
return pi * Math.pow(shape.radius, 2);
}
return shape.width * shape.height;
};
const c = { radius: 20 }; // typescript infer the type
const r = { width: 10, height: 8 }; // typescript infer the type
console.log(getAreaGeneric(c));
console.log(getAreaGeneric(r));