🔷 TypeScript Intermediate

What are discriminated unions in TypeScript?

Why Interviewers Ask This

Mid-level TypeScript roles require deep understanding of this topic. Interviewers ask this to separate candidates who truly understand the mechanics from those who only know surface-level concepts.

Answer

A discriminated union (also called tagged union or algebraic data type) is a pattern where a union's members each have a common literal property (the discriminant) that TypeScript uses to narrow the type. Example: type Shape = | { kind: "circle"; radius: number } | { kind: "rectangle"; width: number; height: number } | { kind: "triangle"; base: number; height: number };. The kind property is the discriminant. When you check shape.kind, TypeScript narrows the type to the matching member: switch (shape.kind) { case "circle": return Math.PI * shape.radius ** 2; case "rectangle": return shape.width * shape.height; }. If you add a new variant to the union but forget to handle it in the switch, TypeScript flags the error (if you add a default case that assigns to never). Discriminated unions are a core pattern for modeling complex state in TypeScript — error/success responses, UI states (loading/loaded/error), form validation states, etc.

Pro Tip

Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex TypeScript answers easy to follow.