...

/

Review: Type Composition and Variants

Review: Type Composition and Variants

Review the key type composition tools—unions, discriminated unions, interfaces, and intersections for modeling real-world variants.

This chapter focused on how to model variation in shape, meaning, and behavior using TypeScript’s type system. The structure of data tells us what it is, and the compiler makes sure we never misunderstand it.

We’ve gone from simple constraints like "asc" | "desc" to full-blown pattern matching on real-world API responses. Let’s connect the dots.

Literal and union types: Precision and possibilities

Literal types let us treat exact values like "dark", 42, or true as types. Union types group those exact values into controlled sets—tight enough for safety, flexible enough for real-world use.

type Direction = "up" | "down";
let move: Direction = "up";
Union types allow a variable to be one of several specific values

Every possible value is now explicit. This gives us both clarity and type safety.

But unions come with a trade-off: their flexibility means we need to be explicit about which variant we're working with. TypeScript won’t let us use a value until we narrow its type. That’s where ...