Using Literal and Union Types

Learn how to constrain types precisely using literal types and model flexible behavior using unions while avoiding pitfalls from ambiguity.

We’ve already met union and literal types like "admin" | "editor" and string | null. But if that’s all we’re doing with them, we’re not really using TypeScript—we’re just naming things.

This lesson covers how to constrain values, build variant logic without enums, and avoid the kind of ambiguity that leaves our logic error-prone.

Literal types: Values as types

In JavaScript, we think of "dark" as a value. In TypeScript, we can make it a type.

This is the essence of a literal type: a concrete, exact value like "light"42, or true being treated as a type. It’s no longer one value among many—it’s the only valid value.

Let’s compare two assignments: