Explain it simply
Unions and aliases, in plain language
A union type says "this value is one of these". string | number means the value is a string or a number, and nothing else. You write it with the pipe character |, which you can read aloud as "or".
A type alias gives a type a name with the type keyword. Write type ProductId = string | number once, and then use ProductId everywhere instead of repeating the whole union. Aliases keep long types readable and make sure every place that uses them stays in sync.
Problem → Why → Solution
The problem: one type is too narrow, any is too wide
An online shop has product IDs that are numbers for old products and strings like "sku-2048" for new ones. Typing the parameter as number rejects the new IDs; typing it as any accepts everything, including undefined and whole objects. A developer copies string | number into eight functions, and when a third ID format arrives, two of the eight copies are missed.
function findProduct(id: number) { /* ... */ }
findProduct("sku-2048"); // error: string is not assignable to number
function removeProduct(id: any) { /* ... */ }
removeProduct({ id: 7 }); // compiles, but is clearly wrongWhat is missing
A single type is too narrow and any is too wide. You need a way to list exactly the types that are allowed, and a way to write that list once so every function shares the same definition.
Core concept: sets of values, allowed operations and names
A union A | B describes a value that is either an A or a B. Think of it as joining sets of allowed values: string | number accepts every string and every number. You can combine any types, including literal types: type Status = "idle" | "loading" | "done" accepts exactly three strings. Adding null or undefined, as in string | null, is how TypeScript says a value may be missing when strictNullChecks is on.
The flip side matters just as much. Because TypeScript does not know which member a union value currently holds, it only allows operations that are valid for every member. On string | number you can call toString(), since both types have it, but not toUpperCase(), which only strings have. The wider the union, the fewer operations are allowed directly. Picking out the right member before using it is called narrowing, and it is the topic of the next lesson.
| Value's type | Allowed without narrowing | Not allowed yet |
|---|---|---|
| string | number | toString(), "ID: " + value | toUpperCase(), toFixed(2) |
| { name; age } | { name; email } | .name (both members have it) | .age, .email |
| "S" | "M" | "L" | comparing with ===, using it as a string | assigning "XL" |
A type alias names a type: type Name = SomeType. The right-hand side can be anything: a union, an object shape, a tuple or a function type. Aliases do not create new types; they are only names. type UserId = string and type OrderId = string are both just string, so the compiler happily accepts an OrderId where a UserId is expected. Use aliases for readability and single-point changes, not to keep apart values that share a base type.
Write the union once, share it everywhere
-----------------------------------------
type ProductId = string | number; <- the union is written once
function findProduct(id: ProductId) <- every function refers to it
function removeProduct(id: ProductId)
function logProduct(id: ProductId)
Change the alias later:
type ProductId = string | number | bigint
-> all three functions pick up the new member automatically- List the allowed types: A | B
- Name it once: type Alias = A | B
- Use only what every member has
- Narrow to reach member-only parts
A union widens what a value can be and narrows what you can do with it until you check.
General pattern
type Alias = TypeA | TypeB; // union of types
type Choice = "first" | "second"; // union of literal values
type MaybeValue = Value | null; // a value that may be missing
type Shape = { field: Type }; // alias for an object shape
type Handler = (input: Input) => Output; // alias for a function type
function name(param: Alias): Result { /* ... */ }| joins types with "or", and type Name = ... names any type. Then use the alias in annotations exactly like any other type.
One function, two ID formats
The example names a union with an alias and uses it for a function that accepts both ID formats. Each console.log call prints its own line, so the output has two lines.
// Type Alias for a complex type
type StringOrNumber = string | number;
function printId(id: StringOrNumber) {
console.log("Your ID is: " + id);
}
printId(101);
printId("abc-101");Code breakdown
- Line 2
type StringOrNumber = string | number;Names the union string | number as StringOrNumber. Nothing of this line remains at runtime.
- Line 4
function printId(id: StringOrNumber) {The parameter uses the alias, so it accepts both strings and numbers.
- Line 5
console.log("Your ID is: " + id);Concatenating with a string is valid for both members (a number is converted to text), so no narrowing is needed. id.toUpperCase() here would be an error.
- Lines 8-9
printId("abc-101");printId(101) and printId("abc-101") both compile. printId(true) would be a compile error, because boolean is not in the union.
Your ID is: 101
Your ID is: abc-101Unions of object shapes
The rule is the same when the members are object types: you can only read properties that every member has. Below, method exists on both members, but last4 only exists on card payments. Checking method to reach last4 is the discriminated-union pattern you will meet in the next lesson.
type CardPayment = { method: "card"; last4: string };
type CashPayment = { method: "cash" };
type Payment = CardPayment | CashPayment;
function describe(p: Payment): string {
// p.method exists on both members, so this is allowed.
// p.last4 would be an error: CashPayment has no last4.
return `Paid by ${p.method}`;
}
console.log(describe({ method: "card", last4: "4242" })); // Paid by card
console.log(describe({ method: "cash" })); // Paid by cash| Type | Meaning |
|---|---|
| (string | number)[] | one array that may mix both: [1, "two", 3] |
| string[] | number[] | an all-string array or an all-number array |
| string | number[] | a single string, or an array of numbers |
In real projects
Real project: UI component props and API data
Frontend code is full of literal unions: a button size of "sm" | "md" | "lg", a theme of "light" | "dark" | "system". When someone using the component types "medium", they see a red underline in the editor instead of a broken layout in the browser. On the backend you meet nullable columns such as deletedAt: Date | null and function-type aliases for callbacks. Naming the whole props type with an alias lets the component and its tests share one definition:
type ButtonSize = "sm" | "md" | "lg";
type ClickHandler = (label: string) => void;
type ButtonProps = {
label: string;
size?: ButtonSize;
onClick: ClickHandler;
};
function renderButton(props: ButtonProps): string {
const size = props.size ?? "md";
return `<button class="btn-${size}">${props.label}</button>`;
}
console.log(renderButton({ label: "Save", onClick: () => {} }));
// renderButton({ label: "Save", size: "medium", ... }) would not compileAPI code follows the same pattern. Declare the state of a request as type LoadState = "idle" | "loading" | "success" | "error", and every piece of UI code knows there are exactly four states to handle. The day the product team adds a "cancelled" state, you change one alias and every file that uses the type sees the change immediately.
Common mistakes
Common mistakes
1. Expecting an alias to keep IDs apart
Declare type UserId = string and type OrderId = string, then call cancelOrder(id: OrderId) with a user ID: the compiler says nothing, because both are just string. If you really need to stop that mix-up, you need a dedicated technique such as branded types; a plain alias is not enough.
2. Forcing a member-only method with as
When toUpperCase() is rejected on a string | number value, it is tempting to write (id as string).toUpperCase(). That only silences the compiler: the day id is 101, it crashes at runtime with a TypeError. Use narrowing to handle each member instead.
3. Forgetting parentheses in array types
string | number[] means "a string, or an array of numbers", not "an array of strings and numbers". For a mixed array, write (string | number)[] with parentheses.
Best practices
Best practices
- Give a union an alias as soon as more than two functions use it.
- Prefer a literal union over a wide string when the list of options is fixed.
- Put | null or | undefined in the type explicitly when a value may be missing.
- Never bypass a union with any or as; narrow it instead.
- Name aliases after their purpose (ProductId) rather than their shape (StringOrNumber).
Mini challenge
T-shirt order lines
Model the order lines of an online shop with a literal union, a nullable field and object type aliases, then print the total price of each line.
- Declare type Size = "S" | "M" | "L" | "XL".
- Declare type PriceTable with one number property per Size.
- Declare type OrderLine with item, size, quantity and giftNote: string | null.
- lineTotal(line, table) returns table[line.size] * line.quantity.
- describeLine(line) shows "no gift note" via ?? when there is no note.
// TODO: type Size = four literal sizes
// TODO: type PriceTable = one number property per size
// TODO: type OrderLine = { item, size, quantity, giftNote (string or null) }
function lineTotal(line: OrderLine, table: PriceTable): number {
// TODO: look up the price for line.size and multiply by quantity
return 0;
}
function describeLine(line: OrderLine): string {
// TODO: "2 x T-shirt (M) = $18, no gift note"
return "";
}
// TODO: create two order lines and print describeLine() for eachExpected: Two lines: "2 x T-shirt (M) = $18, no gift note" and "1 x Hoodie (XL) = $12, Happy birthday!". Writing size: "XXL" is a compile error.
Show hint
line.size has type Size, which matches the keys of PriceTable exactly, so table[line.size] works without narrowing. line.giftNote ?? "no gift note" falls back when the note is null.
Show solution
type Size = "S" | "M" | "L" | "XL";
type PriceTable = { S: number; M: number; L: number; XL: number };
type OrderLine = {
item: string;
size: Size;
quantity: number;
giftNote: string | null;
};
const prices: PriceTable = { S: 8, M: 9, L: 10, XL: 12 };
function lineTotal(line: OrderLine, table: PriceTable): number {
return table[line.size] * line.quantity;
}
function describeLine(line: OrderLine): string {
const note = line.giftNote ?? "no gift note";
const total = lineTotal(line, prices);
return `${line.quantity} x ${line.item} (${line.size}) = $${total}, ${note}`;
}
const order: OrderLine[] = [
{ item: "T-shirt", size: "M", quantity: 2, giftNote: null },
{ item: "Hoodie", size: "XL", quantity: 1, giftNote: "Happy birthday!" },
];
for (const line of order) console.log(describeLine(line));Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A union A | B describes a value that is an A or a B; literal unions model fixed lists of options.
- Before narrowing, you can only use operations that every member of the union shares.
- type Name = ... names any union, object shape or function type and gives you one place to change it.
- An alias is only a name; it does not keep apart values that share a base type.
TypeScript Handbook — TypeScript