Union and literal types
Overview
Real data often comes in several forms: an ID that’s a string or a number, a setting that’s one of three values, a result that’s either data or an error. Union types describe “one of these”, and literal types describe exact values. Together they’re one of TypeScript’s most powerful — and most used — features.
Union types
Join types with |:
let id: string | number;
id = "a-42"; // ✓
id = 42; // ✓
id = true;
// error TS2322: Type 'boolean' is not assignable to type 'string | number'.Unions work anywhere a type goes:
function show(value: string | string[]) { … }
type Result = Data | Error;
const items: (string | number)[] = [1, "two"]; // brackets matter: an array of eitherYou can only use what they share
If a value might be a string or a number, TypeScript only lets you do things that work for both:
function format(id: string | number) {
id.toString(); // ✓ both have toString
id.toUpperCase();
// error TS2339: Property 'toUpperCase' does not exist on type 'string | number'.
// Property 'toUpperCase' does not exist on type 'number'.
}That’s exactly right: if id were a number, toUpperCase would crash. To use string-only methods, first check that it is a string:
function format(id: string | number): string {
if (typeof id === "string") {
return id.toUpperCase(); // here id: string
}
return id.toFixed(0); // here id: number
}This is narrowing: TypeScript follows your check and knows which member of the union you have in each branch. Type narrowing covers every way to narrow.
Literal types
A literal type is a type with exactly one value:
let direction: "left" = "left";
direction = "right";
// error TS2322: Type '"right"' is not assignable to type '"left"'.On their own they’re not very useful. Combined into a union, they describe a fixed set of options:
type Size = "sm" | "md" | "lg";
type Direction = "up" | "down" | "left" | "right";
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";
type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6;
type Toggle = true | false; // that's just booleanWhat you get:
- Typos are compile errors:
"lg "or"large"won’t pass. - Autocomplete offers the options as you type the opening quote.
- Self-documenting signatures:
resize(size: Size)tells callers exactly what’s allowed — no need to read the code or docs. - Narrowing works on each option: after
if (size === "sm") return …, TypeScript knowssizeis"md" | "lg".
When literal types get widened
type Size = "sm" | "md" | "lg";
function padding(size: Size) { … }
let s = "sm"; // let s: string — widened!
padding(s);
// error TS2345: Argument of type 'string' is not assignable to parameter of type 'Size'.
const t = "sm"; // const t: "sm"
padding(t); // ✓A let can be reassigned to any string, so TypeScript widens its type to string, which is too wide for Size. Fixes: use const, annotate (let s: Size = "sm"), or use as const for objects and arrays (as const and satisfies).
Unions of object types
Unions aren’t just for primitives:
type Cat = { name: string; meow(): void };
type Dog = { name: string; bark(): void };
function call(pet: Cat | Dog) {
console.log(pet.name); // ✓ both have name
pet.meow();
// error TS2339: Property 'meow' does not exist on type 'Cat | Dog'.
}Telling object types apart is the job of the in operator, custom type guards and — best of all — discriminated unions, which get their own lesson.
Unions vs overloads vs generics
You now have three tools for flexible functions:
- Union parameter — the function accepts several types and returns the same kind of thing either way:
formatId(id: string | number): string. - Overloads — the return type depends on which type came in (Parameters and overloads).
- Generics — the output type follows the input type exactly (Generic functions).
Reach for the union first; it’s the simplest.
Literal unions instead of magic strings
A lot of JavaScript code passes around “magic strings”: setStatus("actve") — oops. Every time you see a parameter that only accepts a few specific values, give it a literal union. It costs one line and eliminates a whole category of bugs.
Remember:
|means “one of these”; literal types pin values down exactly; and you must narrow a union before using anything that only some members have.
A button style picker
Define type Size = "sm" | "md" | "lg" and type Variant = "primary" | "secondary" | "danger". Write padding(size: Size): string returning "4px 8px", "8px 16px" or "12px 24px". Write buttonClass(variant: Variant, size: Size = "md", disabled = false): string returning e.g. "btn btn-danger btn-lg", with is-disabled added when disabled. Write formatId(id: string | number): string that pads numbers to 6 digits (42 → "000042") and upper-cases strings. Print a few results, and show with // @ts-expect-error that buttonClass("warning") and padding("xl") are rejected.
type Size = "sm" | "md" | "lg";
type Variant = "primary" | "secondary" | "danger";
// padding()
// buttonClass()
// formatId()type Size = "sm" | "md" | "lg";
type Variant = "primary" | "secondary" | "danger";
function padding(size: Size): string {
if (size === "sm") return "4px 8px";
if (size === "md") return "8px 16px";
return "12px 24px"; // size: "lg" — the only option left
}
function buttonClass(variant: Variant, size: Size = "md", disabled = false): string {
const classes = ["btn", `btn-${variant}`, `btn-${size}`];
if (disabled) classes.push("is-disabled");
return classes.join(" ");
}
function formatId(id: string | number): string {
if (typeof id === "number") return id.toString().padStart(6, "0");
return id.toUpperCase();
}
console.log(padding("lg")); // 12px 24px
console.log(buttonClass("danger", "lg")); // btn btn-danger btn-lg
console.log(buttonClass("primary", "sm", true)); // btn btn-primary btn-sm is-disabled
console.log(formatId(42), formatId("ab-7")); // 000042 AB-7
// @ts-expect-error -- "warning" is not a Variant
buttonClass("warning");
// @ts-expect-error -- "xl" is not a Size
padding("xl");Summary
- A union type
A | Baccepts a value of either type. - Literal types allow exact values:
"sm" | "md" | "lg"is a precise, self-documenting set of options. - With a union, you can only use what every member supports — narrow it first to use the rest.
- Comparing with
===or checkingtypeofnarrows a union inside that branch. - Literal unions replace magic strings and most enums: typos become compile errors and the editor autocompletes the options.