Sub topic 2
Literal unions for a fixed set of values
This chapter assumes you know basic TypeScript syntax, type aliases, and function parameter and return types. You should also know what a union such as string | number means. Here you will restrict a union to specific values, so the compiler rejects anything outside a fixed set.
Literal types
A literal type is a type that contains exactly one value. The string "north" has a literal type "north". The number 42 has a literal type 42. The booleans true and false are literal types too, and boolean is just the union true | false.
TypeScript infers a literal type when the value can never change. It infers the wider type when the value can change:
const a = "north"; // type "north"
let b = "north"; // type stringA const binding can't be reassigned, so a keeps the narrow type "north". A let binding can be reassigned, so TypeScript widens b to string. This widening behavior explains most of the surprises later in this chapter.
Combining literals into a union
One literal type is rarely useful. A union of several literals describes a closed set of allowed values:
type Direction = "north" | "south" | "east" | "west";
function isNorth(d: Direction): boolean {
return d === "north";
}
console.log(isNorth("north")); // true
// @ts-expect-error: "up" is not one of the four directions
console.log(isNorth("up"));The call isNorth("up") fails at compile time. The error message names the allowed values, and editors use the same information to offer autocomplete for the argument.
A literal union also protects comparisons. Inside isNorth, writing d === "up" is an error, because d can never be "up":
type Direction = "north" | "south" | "east" | "west";
function isUp(d: Direction): boolean {
// @ts-expect-error: this comparison has no overlap
return d === "up";
}A typo in a comparison is therefore caught as well as a typo in an argument. With a plain string parameter, both mistakes compile without complaint.
Handling every member
A function over a literal union usually needs a result for each member. A switch makes that easy to read:
type Direction = "north" | "south" | "east" | "west";
function turnAround(d: Direction): Direction {
switch (d) {
case "north": return "south";
case "south": return "north";
case "east": return "west";
case "west": return "east";
}
}
console.log(turnAround("east")); // westThe function has no return after the switch, and it still compiles. In each case, TypeScript removes the matched literal from the type of d. After the fourth case nothing remains, so it knows the end of the function can't be reached.
This gives you a safety check for free. Add "up" to Direction and the function stops compiling. The error says the function lacks an ending return statement and the return type does not include undefined. The compiler points you to every place that must handle the new value. A later chapter in this tutorial makes this check explicit with never.
Number and boolean literal unions
Strings are the most common literals, but numbers work the same way:
type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6;
function roll(): DiceRoll {
return (Math.floor(Math.random() * 6) + 1) as DiceRoll;
}
function isSix(r: DiceRoll): boolean {
return r === 6;
}
console.log(isSix(roll()));The as DiceRoll assertion is needed because Math.random() produces a plain number. The compiler can't prove the arithmetic stays between 1 and 6. An assertion like this is your promise to the compiler. If the arithmetic were wrong, TypeScript wouldn't catch it. Keep assertions at the edge where a value enters your typed code, and keep the logic behind them simple.
Boolean literals are useful for correlating fields. For example, { ok: true; value: string } | { ok: false; error: string } is a union whose shape depends on a boolean. Later chapters build on that pattern.
Where literal types get lost
Widening is the most common problem with literal unions. A literal type can silently turn back into string before it reaches the function that needs it.
type Method = "GET" | "POST";
function request(url: string, method: Method): void {
console.log(`${method} ${url}`);
}
const options = { method: "GET" };
// @ts-expect-error: options.method has type string
request("/users", options.method);The variable options is const, but the object's properties are still mutable. TypeScript assumes you might later write options.method = "banana", so it infers string for the property. The check fails even though the value is "GET".
The diagram shows where each fix applies.
There are three ways to keep the literal type.
type Method = "GET" | "POST";
function request(url: string, method: Method): void {
console.log(`${method} ${url}`);
}
// 1. Annotate the variable
const typed: { method: Method } = { method: "GET" };
request("/users", typed.method);
// 2. Freeze the whole object with `as const`
const frozen = { method: "GET" } as const;
request("/users", frozen.method);
// 3. Assert one value in place
const inline = { method: "GET" as const };
request("/users", inline.method);Choose among them based on how much of the object should be fixed:
| Technique | Effect | Use when |
|---|---|---|
| Type annotation | Properties get the declared type | The object has a named type you can reuse |
| `as const` on an object | Every property becomes `readonly` with a literal type | The whole object is a fixed constant |
| `as const` on one value | Only that value keeps its literal type | One property is the problem |
Note that as const also makes properties readonly. If other code mutates the object, option 1 is the better fit.
Contextual typing keeps literals for you
Widening only happens when TypeScript has no expected type to work with. When you write a literal directly where a literal union is expected, the expected type tells TypeScript to keep the literal:
type Method = "GET" | "POST";
function request(url: string, method: Method): void {
console.log(`${method} ${url}`);
}
request("/users", "POST"); // fine, no widening
const handlers: Record<string, Method> = { users: "GET" }; // also fineThis is why most everyday code works without as const. The problems appear when you first store the value in an unannotated variable and use it later.
One source of truth: deriving the union from an array
A literal union written by hand has a downside. If you also need the values at runtime, for example to fill a dropdown or validate input, you must write the list twice. The two copies can drift apart. Declare the values once as a readonly tuple and derive the type from it:
const DIRECTIONS = ["north", "south", "east", "west"] as const;
type Direction = (typeof DIRECTIONS)[number];
function isDirection(value: string): value is Direction {
return (DIRECTIONS as readonly string[]).includes(value);
}
function parseDirection(input: string): Direction | undefined {
return isDirection(input) ? input : undefined;
}
console.log(parseDirection("east")); // "east"
console.log(parseDirection("up")); // undefinedRead the type expression from the inside out:
typeof DIRECTIONSis the type of the constant:readonly ["north", "south", "east", "west"].[number]indexes that tuple with any number, which yields the union of all element types.
Without as const, the array would be typed string[] and the union would collapse to string.
isDirection is a type guard. Its return type value is Direction tells the compiler that when the function returns true, the argument is a Direction. The cast to readonly string[] is needed because includes on a tuple of literals only accepts those literals as its argument. The compiler can't check that your guard body is correct, so the guard is the one place where the runtime and the type must agree.
Types disappear at runtime
TypeScript removes all types when it compiles to JavaScript. A Direction parameter does not stop a caller from passing "up" at runtime if the value came from JSON, a URL, a form field, or an untyped library. The compiler checks only the code it can see.
Treat data from outside your program as string or unknown and validate it before it enters typed code. The isDirection guard above is the pattern: validate once at the boundary, and the rest of your code works with the narrow type and no further checks.
Mapping every member
A Record keyed by a literal union forces you to provide an entry for every member:
type Direction = "north" | "south" | "east" | "west";
const opposite: Record<Direction, Direction> = {
north: "south",
south: "north",
east: "west",
west: "east",
};
console.log(opposite["east"]); // westIf you delete the west line, or add "up" to Direction without adding an entry, the object no longer matches the type and the compiler reports the missing key. This is a lookup-table alternative to the switch shown earlier. It suits cases where each member maps to plain data and no logic is needed.
Literal unions compared with enums
TypeScript also has enum. For a fixed set of values, the two features overlap:
| Aspect | Literal union | `enum` |
|---|---|---|
| Runtime code generated | None | An object (except `const enum`) |
| Value written by callers | The raw value, `"north"` | The enum member, `Direction.North` |
| Works with JSON and external data | Directly, after validation | Needs mapping for string enums |
| Iterating the values | Needs an array such as `DIRECTIONS` | Built in with `Object.values` for string enums |
| Fits erasable-syntax-only tooling | Yes | No, because enums emit code |
Literal unions are the lighter option and are usually preferred in modern TypeScript. Enums remain reasonable when you want a runtime object and a namespace for the values, or when you work in a codebase that already uses them.
Common mistakes
- Forgetting that
letwidens.let heading = "north"has typestring. Annotate it:let heading: Direction = "north". - Forgetting
as conston the array. Without it,(typeof DIRECTIONS)[number]isstring, and every check passes. - Trusting external input. A literal union is a compile-time promise. Validate values that come from outside.
- Wide unions that gain no safety.
"a" | "b" | stringcollapses tostring, because every literal is already astring.
Summary
A literal union limits a value to a fixed set, and the compiler rejects typos in arguments and comparisons. Literals widen to string or number when TypeScript has no expected type, so use an annotation or as const to keep them. Derive the union from a readonly tuple when you also need the values at runtime, and validate external data with a type guard.
Exercise
The code below fails to compile at the call to paint. Explain why, then give two different fixes.
type Color = "red" | "green" | "blue";
function paint(c: Color): void {
console.log(painting ${c});
}
let favorite = "red";
paint(favorite);
Show answer
favorite is declared with let, so TypeScript widens its type from the literal "red" to string, and string is not assignable to Color. Fix 1: annotate the variable, let favorite: Color = "red";. Fix 2: declare it with const favorite = "red";, which keeps the literal type "red". Writing let favorite = "red" as const; also works.
Exercise
You have const SIZES = ["small", "medium", "large"] and want a Size type that stays in sync with the array. Write the declaration so that Size is "small" | "medium" | "large", and say what Size would be if you forgot the part that makes it work.
Show answer
Write const SIZES = ["small", "medium", "large"] as const; and type Size = (typeof SIZES)[number];. The as const makes the array a readonly tuple of literal types. Without it, the array has type string[], so Size would be just string, and the compiler would accept any string.