Sub topic 2
Literal unions for a fixed set of values
Assume you know basic TypeScript syntax, type annotations, object types, type aliases, and function parameter and return types. This chapter uses those ideas to model values that must come from a small, known set.
What a literal union is
A literal type describes one exact value. For example, "north" is a string literal type, while string describes any string.
A union type combines alternatives with the | operator. A literal union therefore describes a value that must equal one of several exact values:
type Direction = "north" | "south" | "east" | "west";
let heading: Direction = "north";
heading = "west";
// Error: "up" is not one of the allowed directions.
// heading = "up";The Direction type does not accept an arbitrary string. It accepts only the four listed strings. This gives you a useful boundary between valid and invalid data.
Literal unions work with numbers and booleans too:
type HttpStatus = 200 | 201 | 400 | 404 | 500;
type Retryable = true | false;
const status: HttpStatus = 404;
const shouldRetry: Retryable = false;A literal union is different from an enum. An enum creates a runtime object that can be used by JavaScript. A literal union usually disappears after TypeScript compiles your code. Use a literal union when you mainly need compile-time checking and ordinary strings or numbers are enough.
Why literal inference matters
TypeScript sometimes widens a literal to a broader type. A const variable cannot be reassigned, so TypeScript usually keeps its exact literal type. A let variable may change, so TypeScript usually infers a broader type:
const fixedDirection = "north";
// Type: "north"
let changingDirection = "north";
// Type: string
changingDirection = "west";The second variable has type string, not Direction. You can still assign it to a Direction value only after checking that its value is valid.
An explicit annotation preserves the intended domain:
let direction: Direction = "north";
direction = "east";Use an annotation when a variable represents a meaningful domain such as a direction, status, theme, or permission level.
Using literal unions in functions
A function parameter typed with a literal union documents and enforces its accepted inputs:
type Direction = "north" | "south" | "east" | "west";
function turnAround(direction: Direction): Direction {
switch (direction) {
case "north":
return "south";
case "south":
return "north";
case "east":
return "west";
case "west":
return "east";
}
}
console.log(turnAround("north")); // south
// turnAround("up"); // ErrorThe compiler checks calls at compile time. It also knows that direction can be only one of the four cases inside the function.
Deriving a union from values
When the allowed values also need to exist at runtime, define an immutable array and derive the union from it:
const directions = ["north", "south", "east", "west"] as const;
type Direction = (typeof directions)[number];
function isDirection(value: string): value is Direction {
return directions.includes(value as Direction);
}
console.log(isDirection("north")); // true
console.log(isDirection("up")); // falseas const prevents the array elements from widening to string. The expression (typeof directions)[number] means “the type of any element in this array,” producing the union "north" | "south" | "east" | "west".
Without as const, TypeScript would infer string[], and the derived element type would be only string. That would lose the fixed-set guarantee.
Choosing useful union members
Use names that match the values your program actually receives. Keep the set small and intentional.
- Use
"draft" | "published"for a document state. - Use
"light" | "dark"for a display theme. - Use
1 | 2 | 3 | 4 | 5for a five-level rating. - Use
stringwhen any string is valid.
A union with many unrelated values can become difficult to maintain. If each alternative has different data, a discriminated union, covered later, usually models it more clearly.
Exercise
Define a type named LogLevel that accepts only "debug", "info", "warn", or "error", then declare a variable with that type and assign it "warn".
Show answer
type LogLevel = "debug" | "info" | "warn" | "error"; let level: LogLevel = "warn";