Union & Literal Types 🔀
Model ‘one of these exact values’ precisely.
A union (|) says a value is one of several types. A literal type narrows it to one exact value. Together they're TypeScript's superpower.
Literal types
Instead of string, accept only specific strings:
type Direction = "up" | "down" | "left" | "right";function move(d: Direction) { /* ... */ }move("up"); // ok
move("north"); // error: not a Direction
Narrowing
TypeScript narrows the type as you check it:
type Status = "loading" | "success" | "error";function render(s: Status) {
if (s === "error") {
// s is "error" here
return "Something broke";
}
return s; // s is "loading" | "success"
}Combine with switch for exhaustive handling — every case covered, compiler-verified.
Get Marcelo Domingues’s stories in your inbox
Join Medium for free to get updates from this writer.
TL;DR: Unions + literals replace loose string/number with a precise set of allowed values.
Swap a stringly-typed parameter for a literal union and watch the bugs vanish.







