Introduction
Real data is often one of several kinds: an ID that is a number or a string, a payment by card or in cash, an order that is pending, paid or refunded. Union types describe exactly that, and type aliases give such types names. Together they let the type checker know every case a value can be, and make sure your code handles each one.
How it works
A type alias names a type: type ID = number | string. Unlike an interface, it can name any type, including unions, tuples and function types.
A union type A | B holds a value of one of its members. Before you use member-specific operations, you must find out which member you have: on an ID you may use what numbers and strings share, such as toString(), but not toFixed(). The next lesson covers how to check.
A literal union lists exact values: type Status = "pending" | "paid" | "refunded". A variable of that type can hold only those three strings, so a typo such as "payed" is a type error, and editors suggest the valid values as you type. Literal unions are the usual TypeScript replacement for free-text status fields.
An intersection type A & B has all the properties of both. It is useful for adding common fields to several shapes: (Card | Cash) & { id: ID; amount: number } is a card or cash payment that always has an id and an amount.
A discriminated union is a union of object types that share a field holding a different literal in each, such as method: "card" and method: "cash". Checking that field tells TypeScript which member you have: after p.method === "card", it knows p.last4 exists. This pattern is the backbone of most well-typed programs, from reducers in web apps to messages between services.
Example
// Type aliases, unions of literals, and an intersection.
type ID = number | string;
type Status = "pending" | "paid" | "refunded";
type Card = { method: "card"; last4: string };
type Cash = { method: "cash" };
type Payment = (Card | Cash) & { id: ID; amount: number; status: Status };
function describe(p: Payment): string {
const how = p.method === "card" ? "card ending " + p.last4 : "cash";
return "#" + p.id + ": " + p.amount + " by " + how + " (" + p.status + ")";
}
const payments: Payment[] = [
{ id: 1, amount: 250, status: "paid", method: "card", last4: "4242" },
{ id: "A7", amount: 80, status: "pending", method: "cash" },
];
for (const p of payments) console.log(describe(p));
let state: Status = "pending";
state = "refunded"; // "lost" would be an error: it is not one of the three
console.log(state);Line by line
IDmay be a number or a string;Statusmay be one of three exact strings.CardandCashshare the fieldmethod, with a different literal in each: a discriminated union.Paymentaddsid,amountandstatusto either kind with an intersection.- In
describe, afterp.method === "card", TypeScript allowsp.last4. statecan change from one allowed status to another, but to nothing else.
Expected result
#1: 250 by card ending 4242 (paid)
#A7: 80 by cash (pending)
refunded
In the real world
Payment providers, HTTP libraries and UI frameworks describe their data with discriminated unions: a request is loading, has succeeded with data, or has failed with an error, and each state carries different fields. Literal unions describe HTTP methods, log levels and CSS keywords. Because the compiler knows every member, adding a new one makes it list every place that does not handle it yet.
Common mistakes
- Using a member-specific property before checking which member you have: on a union, only shared properties are allowed.
- Confusing | and &: a union of two object types does not have both sets of properties.
- Using string where a literal union fits, losing the checks on typos.
- Giving the members of a discriminated union different field names for the discriminant; it must be the same field in each.
Best practices
- Model every "one of several kinds" in your data as a discriminated union with a
kindortypefield. - Prefer literal unions to free-text strings for statuses and options.
- Give repeated or complex types a name with a type alias.
Summary
Type aliases name types. A union A | B is one of its members, an intersection A & B has the properties of both, and a literal union restricts a value to a fixed list. A discriminated union shares a literal field across its members, and checking that field tells TypeScript exactly which member it has.
Quick check
Key takeaways
- A | B means one of them; A & B means both at once.
- Unions of string literals give a variable a fixed list of allowed values.
- A shared literal field (a discriminant) tells TypeScript which member of a union a value is.
Practice problems for this lesson
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.