JS Built-ins
TypeScriptintermediate

Interface β€” Discriminated Union

πŸ“– Usage Example
type Shape = { kind: 'circle'; r: number } | { kind: 'rect'; w: number; h: number }
switch (shape.kind) {
  case 'circle': return Math.PI * shape.r ** 2
  case 'rect':   return shape.w * shape.h
}

A discriminated union uses a shared literal property to select the correct variant.

Discriminated Unions

A discriminated union uses a shared literal property (the discriminant) to distinguish union members.

Challenge: Implement processShape(shape) that calculates area for circles and rectangles.

processShape({ kind: 'circle', radius: 1 })           // β†’ Math.PI
processShape({ kind: 'rect', width: 3, height: 4 })   // β†’ 12
πŸ’‘ Hints (1)
  • β€’ After the if check, TypeScript knows exactly which shape you have β€” no cast needed.