RUN

Union types and narrowing in TypeScript

Handle values that can be one of several types. Press Run to try it, then change the code and run it again.

main.ts

type Shape =
  | { kind: 'circle'; radius: number }
  | { kind: 'rectangle'; width: number; height: number };

function area(shape: Shape): number {
  switch (shape.kind) {
    case 'circle':
      return Math.PI * shape.radius ** 2;
    case 'rectangle':
      return shape.width * shape.height;
  }
}

console.log(area({ kind: 'circle', radius: 2 }).toFixed(2));
console.log(area({ kind: 'rectangle', width: 3, height: 4 }));
Output

Press Run to see the output.

More TypeScript examples

Open the full TypeScript online compiler →