Skip to main content

Combining more than two types

Example: combining three or more types

javascript
let value: string | number | boolean; value = "Hello"; // string value = 42; // number value = true; // boolean value = null; // Error - null is not part of the union

That is, value can be a string, a number, or a boolean, but nothing else.


Example with types via type

javascript
type Status = "loading" | "success" | "error" | "idle"; let current: Status; current = "loading"; // ok current = "error"; // ok current = "pending"; // Error - not part of the union

Such string unions are often used for states, roles, statuses, and modes.


Example: combining different structures

javascript
type User = { name: string }; type Admin = { name: string; permissions: string[] }; type Guest = { guestId: number }; type Person = User | Admin | Guest; const a: Person = { name: "Tim" }; // User const b: Person = { name: "Alex", permissions: [] }; // Admin const c: Person = { guestId: 123 }; // Guest

Person can now represent any of the three data shapes.


How many can you combine?

As many as you like. There is no limit on the number of combined types:

javascript
type Many = string | number | boolean | null | undefined | bigint | symbol;

TypeScript handles this without any trouble - what matters is that the code stays readable and meaningful.


Remember

PropertyDescription
Union operator`
Number of typesNot limited
PurposeA variable or function can accept one of the specified values
Common useStatuses, roles, states, different data variants

A real-life example:

javascript
type PaymentMethod = "cash" | "card" | "apple-pay" | "google-pay" | "paypal"; function pay(method: PaymentMethod) { console.log("Payment via:", method); } pay("cash"); // ok pay("paypal"); // ok pay("bitcoin"); // Error - not part of the union

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.