hasinhayder / 100DaysOfCode

100 Days of Code - You know the rest :)

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

ahamed opened this issue · 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));