Real data rarely fits a single fixed shape. A value might be a string or a number; an entity might be both a player and a captain at once. TypeScript expresses these two situations with union types, written with `|`, and intersection types, written with `&`. Unions model 'one of several possibilities' and intersections model 'all of these combined.' This matters because without them you are forced to either widen everything to `any`, losing all safety, or to duplicate code for each variation. Unions let one function accept several input kinds while the compiler tracks exactly which one you have at each point; intersections let you compose a precise combined contract from smaller shapes without rewriting properties. Together they are the algebra of the type system — the operators you reach for constantly to describe data that is alternative or combined — and almost every advanced TypeScript pattern is built on top of them.
35 minintermediate
Union and Intersection Types
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 7 of 35
0% complete