100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
TypeScript Deep Dive
35 minintermediate

Type Guards and Discriminated Unions

When a value can be one of several object shapes, you need a clean, safe way to tell which one you hold and to handle every possibility. Discriminated unions are TypeScript's purpose-built answer: a union of object types that all share a common literal 'discriminant' property, which the compiler uses to narrow the union to a single member with a single check. Paired with type guards, they let you write a `switch` over the discriminant where each branch is automatically the exact member type, and where forgetting a case becomes a compile error. This matters because modelling 'a value that is one of these distinct kinds' is one of the most common shapes in real software — events, results, states, messages — and discriminated unions make that modelling both ergonomic and exhaustive. They are the single most important pattern in this module, the one professionals reach for constantly to make variant data safe.

Analogy🏏Cricket
🏏 Think of it like cricket: Picture how a scoreboard operator constructs every display string from fixed components in a strict format — a batter's line is always built as `${name} ${runs} (${balls})`, never improvised. The format is a template with slots, and only values that fit each slot are allowed. Just as the scoreboard builds each line by filling a fixed template with the right pieces, a template literal type builds a string type by filling a pattern with other types. Just as a stray entry that does not match the format — text where runs should go — is rejected by the operator, a string that does not match the template literal type is rejected by the compiler. Just as the format guarantees every line is readable and consistent, the template type guarantees every string matches the intended shape. This reveals why template literal types matter: strings in software follow patterns just like scoreboard lines, and encoding the pattern into the type makes every malformed string an immediate error.
Lesson 9 of 35
0% complete