JS Built-ins
TypeScriptintermediate

Type Guard β€” discriminated union

πŸ“– Usage Example
type Shape = { kind: 'circle'; r: number } | { kind: 'square'; s: number }
function isCircle(sh: Shape): sh is Extract<Shape, { kind: 'circle' }> {
  return sh.kind === 'circle'
}

Checking the discriminant property narrows a union to a specific member type.

Type Guards: Discriminated Unions

A discriminated union uses a shared literal kind field to distinguish variants.
Use a regular switch or if-check on the literal to narrow the type.

Challenge: Implement getArea(shape: Shape): number using a switch on shape.kind.

getArea({ kind: 'circle', radius: 5 })         // β†’ Math.PI * 25
getArea({ kind: 'rectangle', width: 4, height: 3 })  // β†’ 12
πŸ’‘ Hints (1)
  • β€’ switch(shape.kind) with exhaustive cases β€” TypeScript narrows the type in each branch.