100DaysOfCode icon indicating copy to clipboard operation
100DaysOfCode copied to clipboard

day-1-type-narrowing.ts - generic version.

Open ahamed opened this issue 3 years ago • 0 comments

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));

ahamed avatar May 28 '22 16:05 ahamed