TypeScript Tutorial · TypeScript Basics · Lesson 8 of 25
TypeScript Union and Literal Types
Allow several types with |, restrict values with literal types.
Union types
A | B means "either A or B":
function formatId(id: number | string): string {
return typeof id === "number" ? `#${id.toString().padStart(4, "0")}` : id.toUpperCase();
}
console.log(formatId(42));
console.log(formatId("abc-1"));
Output
#0042 ABC-1
Literal types
A literal type allows exactly one value. Unions of literals model a fixed set of options — often better than an enum:
type Status = "pending" | "paid" | "shipped";
type Size = "S" | "M" | "L";
function label(status: Status): string {
return status === "paid" ? "Paid ✓" : status;
}
let s: Status = "pending";
s = "shipped";
// @ts-expect-error — Type '"lost"' is not assignable to type 'Status'.
s = "lost";
const sizes: Size[] = ["S", "L"];
console.log(label("paid"), sizes);
Output
Paid ✓ [ 'S', 'L' ]
Intersection types
A & B means "both A and B" — it combines object types:
type HasId = { id: number };
type HasTimestamps = { createdAt: string; updatedAt: string };
type Article = HasId & HasTimestamps & { title: string };
const a: Article = { id: 1, title: "Unions", createdAt: "2026-01-01", updatedAt: "2026-02-01" };
console.log(Object.keys(a));
Output
[ 'id', 'title', 'createdAt', 'updatedAt' ]
Test yourself
What does type Answer = "yes" | "no" allow?
Any stringOnly the strings "yes" or "no"A booleanyes or no as variables
Show answer
Answer: Only the strings "yes" or "no"