Exhaustiveness check on a switch

Typescript

Assigning to never makes the compiler fail the build when a new union member is added and left unhandled.

function area(shape: Shape): number {
  switch (shape.kind) {
    case 'circle': return Math.PI * shape.r ** 2;
    case 'square': return shape.side ** 2;
    default: {
      const _exhaustive: never = shape;
      throw new Error(`unhandled: ${_exhaustive}`);
    }
  }
}

More in TypeScript

Random picks