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 unionThat is,
valuecan 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 unionSuch 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
Personcan 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
| Property | Description |
|---|---|
| Union operator | ` |
| Number of types | Not limited |
| Purpose | A variable or function can accept one of the specified values |
| Common use | Statuses, 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 unionShort Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.