Sub topic 9
Literal Types and Unions
This chapter assumes you know basic JavaScript, can run code with tsc or a TypeScript-aware editor, and have read the earlier chapters on inference and on const versus let widening. It covers literal types, union types, and the compiler errors people most often hit when combining them. Narrowing, which is how you work with a union value once you have one, gets its own chapter.
From literal values to literal types
A literal type is a type that allows exactly one value. You have already met one: const name = "Ada" is inferred as the type "Ada", not string. You can also write literal types yourself.
let direction: "north" = "north";
// direction = "south"; // Error: Type '"south"' is not assignable to type '"north"'.
const answer: 42 = 42;
const enabled: true = true;TypeScript has literal types for three kinds of values:
- String literals, such as
"north". - Number literals, such as
42or-1. - Boolean literals,
trueandfalse.
A single literal type is rarely useful on its own. It becomes useful when you combine several into a union.
Union types
A union type lists alternatives separated by |. A value of a union type is one of the listed types, and the compiler does not know which.
type Direction = "north" | "south" | "east" | "west";
function move(dir: Direction, steps: number): string {
return `Moving ${steps} step(s) ${dir}`;
}
move("north", 2); // ok
// move("up", 2); // Error: Argument of type '"up"' is not assignable to parameter of type 'Direction'.The union replaces a loose string with an exact list of allowed values. Typos become compile errors, and editors can offer the allowed values as completions.
Unions are not limited to literals. You can mix any types:
type Id = string | number;
type MaybeName = string | null | undefined;
type Flag = boolean | "unknown";Notice that boolean is itself a union. TypeScript treats it as true | false, which matters when you narrow later.
What you can do with a union value
A union type allows only operations that are valid for every member. This is the rule behind most union errors.
function pad(value: string | number) {
// value.toUpperCase();
// Error: Property 'toUpperCase' does not exist on type 'string | number'.
// Property 'toUpperCase' does not exist on type 'number'.
return value.toString(); // ok: both string and number have toString()
}Reading the error message from the bottom up helps. It names the member of the union that lacks the property. To use toUpperCase, you must first prove the value is a string, which is what narrowing does.
The rule applies in the other direction when you assign. A value of a member type can always be assigned to the union, but a union value can only be assigned to a target that accepts every member.
const id: string | number = "abc-1"; // ok: string is a member
const num: number = id; // see note belowThe second line is subtle. After the first line, the compiler narrows id to string by assignment, so num = id fails with "Type 'string' is not assignable to type 'number'". If id had been a function parameter of type string | number, the error would name the full union instead.
Widening and where literal types get lost
The chapter on const and let explained that let widens a literal to its primitive type. This causes the most common literal-union bug: an object property or variable widens to string before it reaches a function that wants a union.
type Direction = "north" | "south" | "east" | "west";
function go(dir: Direction): void {
console.log(dir);
}
const a = "north";
go(a); // ok: const keeps the literal type "north"
let b = "north";
// go(b); // Error: Argument of type 'string' is not assignable to parameter of type 'Direction'.
const options = { dir: "north" };
// go(options.dir); // Error: properties of a plain object are mutable, so dir is widened to stringThere are three ways to fix this, and each suits a different situation.
- Annotate the variable:
let b: Direction = "north";. - Annotate the object:
const options: { dir: Direction } = { dir: "north" };. - Use
as conston the object, which keeps the literal and makes the property readonly:const options = { dir: "north" } as const;.
Prefer an annotation when the variable is meant to hold any member of the union later. Prefer as const when the value is fixed.
Naming unions with type aliases
A type alias gives a union a name so you can reuse it. Without an alias, the same union repeated in several signatures drifts out of sync.
type Status = "idle" | "loading" | "success" | "error";
interface Request {
url: string;
status: Status;
}
function isFinished(status: Status): boolean {
return status === "success" || status === "error";
}Union types can be built from other unions, and duplicates collapse:
type Primary = "red" | "green" | "blue";
type Extra = "yellow" | "red";
type Color = Primary | Extra; // "red" | "green" | "blue" | "yellow"Deriving a union from a value
Sometimes you already have an array of allowed values and want a union without writing the list twice. Use as const with typeof and an indexed access type.
const STATUSES = ["idle", "loading", "success", "error"] as const;
type Status = (typeof STATUSES)[number];
// "idle" | "loading" | "success" | "error"
function isStatus(value: string): value is Status {
return (STATUSES as readonly string[]).includes(value);
}Here as const turns the array into a readonly tuple of literal types. (typeof STATUSES)[number] asks for the type of any element, which is the union of all of them. The runtime array and the compile-time type now share one source of truth. The value is Status return type is a type predicate. It lets you check a string at runtime and have the compiler treat it as Status afterwards.
Unions and null or undefined
With strictNullChecks on, null and undefined are separate types, so "may be missing" is just a union.
function greet(name: string | undefined): string {
return "Hello, " + (name ?? "stranger");
}
greet("Ada");
greet(undefined);
// greet(); // Error: Expected 1 arguments, but got 0.A parameter typed string | undefined must still be passed. An optional parameter, name?: string, can be omitted. Both give string | undefined inside the function, but the call rules differ.
Discriminating objects with a literal field
Literal types become powerful when a union of object types shares one field whose type is a literal. That field is the discriminant, and checking it narrows the whole object.
type Loading = { status: "loading" };
type Success = { status: "success"; data: string[] };
type Failure = { status: "error"; message: string };
type State = Loading | Success | Failure;
function render(state: State): string {
switch (state.status) {
case "loading":
return "Please wait...";
case "success":
return `Got ${state.data.length} items`;
case "error":
return `Failed: ${state.message}`;
}
}Inside each case, the compiler knows which object type state is, so state.data is only available in the "success" branch. Without the literal discriminant you would need casts or optional fields. Because every case returns, the function needs no default. If you later add a fourth member to State and forget a case, TypeScript reports that the function does not return a value on all paths, as long as strict is on.
Common errors and gotchas
| Symptom | Cause | Fix | Column | Column |
|---|---|---|---|---|
| `string` is not assignable to a literal union | A `let` or mutable object property widened the literal | Annotate the variable, or use `as const` | ||
| Property does not exist on `A \ | B` | Only members common to all alternatives are allowed | Narrow the value first | |
| Allowed values are repeated in several places | No shared alias | Declare one `type`, or derive it from an `as const` array | ||
| Switch compiles after a new member is added | No exhaustive check | Add a `never` check in `default` | ||
| Number literal union rejects computed value | `1 \ | 2 \ | 3` accepts only those exact values | Validate at runtime, or widen to `number` |
Summary of decisions
- Use a literal union when a value has a small, known set of options.
- Use a type alias to name any union used more than once.
- Use a literal discriminant field when each option carries different data.
- Use
as constwith(typeof X)[number]when the list must also exist at runtime. - Treat any value from outside your program as unvalidated, whatever its declared type.
Exercise
Given type Level = "low" | "high"; function set(level: Level) {}, why does let l = "low"; set(l); fail while const l = "low"; set(l); passes? Give two ways to make the let version compile.
Show answer
A let declaration is inferred as string, because the variable can be reassigned and the literal widens. A const keeps the literal type "low", which is a member of Level. To fix the let version, annotate it with let l: Level = "low";, or write let l = "low" as const;, which gives l the type "low". Changing let to const also works.
Exercise
Define const MODES = ["read", "write", "append"] as const;, then derive a type Mode from it. Write a function canWrite(mode: Mode): boolean that returns true for "write" and "append".
Show answer
type Mode = (typeof MODES)[number]; function canWrite(mode: Mode): boolean { return mode === "write" || mode === "append"; } The type Mode is "read" | "write" | "append". Adding a new entry to MODES updates Mode automatically.