TypeScript – Union, Intersection & Literal Types
Basic types like string, number, and boolean are great for starting out, but real-world software is rarely that simple. An API response might return data or an error. A configuration flag might only allow three exact words. A database record might need fields from two different shapes combined together.
TypeScript solves this by letting you combine and restrict types using Unions (|), Intersections (&), and Literal Types. Together, these tools help you build rock-solid state machines and configuration flags that catch bugs before your code ever runs.
- How Union Types (
|) allow a value to be one of several types. - How Literal Types lock variables down to exact strings or numbers for configuration flags.
- How Intersection Types (
&) merge multiple object types into a single combined type. - How to combine Unions and Literals to build type-safe State Machines (Discriminated Unions).
- Common mistakes to avoid and real interview questions senior engineers ask.
1. Quick Overview: Union vs Intersection vs Literal Types
Before writing code, think of these three features like everyday English words: OR, AND, and EXACTLY.
| Feature | Symbol | Plain English Meaning | Example |
|---|---|---|---|
| Union Type | | |
This type OR that type | string | number |
| Intersection Type | & |
This type AND that type combined | User & Timestamps |
| Literal Type | Exact value | EXACTLY this specific string or number | "dark" | "light" or 200 | 404 |
2. Union Types (|) – Allowing Multiple Options
A Union Type lets a variable hold more than one type. You separate the allowed types with a vertical pipe (|). This is very common when dealing with user IDs, form inputs, or API responses where the data could arrive in two different formats.
Working with Union Types and Type Narrowing
When a variable has a union type, TypeScript only lets you use methods that exist on all types in the union. To use a string-specific or number-specific method, you first check the type using typeof. This is called type narrowing.
Example 1: Flexible Customer ID using Union Types
type CustomerId = string | number;
function formatCustomerId(id: CustomerId): string {
if (typeof id === "string") {
// TypeScript knows 'id' is a string here
return `CUST-${id.toUpperCase()}`;
}
// TypeScript knows 'id' is a number here
return `CUST-${id.toFixed(0)}`;
}
console.log(formatCustomerId("abc99"));
console.log(formatCustomerId(4021));
Expected output
CUST-ABC99 CUST-4021
3. Literal Types – Strict Configuration Flags
If you type a variable as string, a developer can pass "production", "prod", or even a typo like "prduction", and TypeScript won't complain. Literal types fix this by restricting a variable to exact string or numeric values.
This is the gold standard for configuration flags, theme settings, log levels, and HTTP status codes.
Example 2: String and Numeric Literals for Configuration Flags
type Environment = "development" | "staging" | "production";
type LogLevel = "debug" | "info" | "error";
type RetryCount = 0 | 1 | 3 | 5;
interface AppConfig {
env: Environment;
logLevel: LogLevel;
maxRetries: RetryCount;
}
const serverConfig: AppConfig = {
env: "production",
logLevel: "error",
maxRetries: 3
};
// serverConfig.env = "prod"; // Compile Error! Type '"prod"' is not assignable.
console.log(`Running in ${serverConfig.env} with ${serverConfig.maxRetries} retries.`);
Expected output
Running in production with 3 retries.
"development" | "staging" | "production") gives you autocomplete in VS Code and catches spelling mistakes immediately while you type—without adding any extra JavaScript code at runtime.4. Intersection Types (&) – Combining Object Shapes
An Intersection Type combines multiple types into one. Using the ampersand (&), the resulting type has all properties from every type you combined. This is ideal for building modular, reusable building blocks in large applications.
Example 3: Combining Reusable Metadata with a User Profile
type Identifiable = {
id: string;
};
type Auditable = {
createdAt: string;
updatedBy: string;
};
type UserProfile = {
name: string;
role: "admin" | "editor" | "viewer";
};
// Intersection: must have properties from ALL three types
type DatabaseUser = Identifiable & Auditable & UserProfile;
const adminUser: DatabaseUser = {
id: "usr_101",
name: "Anita",
role: "admin",
createdAt: "2026-11-19",
updatedBy: "system"
};
console.log(`${adminUser.name} (${adminUser.role}) - ID: ${adminUser.id}`);
Expected output
Anita (admin) - ID: usr_101
type Impossible = string & number;. Because a value cannot be both a string and a number at the exact same time, TypeScript reduces it to the never type, making it unusable.5. Architecture & Workflow Visualized: State Machines
In real-world frontend and backend systems, the most powerful use of Unions and Literals is building a State Machine using a pattern called a Discriminated Union.
Instead of tracking messy boolean flags like isLoading: true and hasError: true at the same time (which creates impossible states), you define each state as its own object with a shared literal property—usually called status.
API Request State Machine (Discriminated Union Flow)
Each box is a distinct type in a Union. Because every branch has a unique literal status, it is impossible to have both data and an error message at the same time.
6. Practical Example – Type-Safe State Machine in Action
Let's put Unions, Intersections, and Literal Types together into a single, production-ready API state handler.
Example 4: Handling an API State Machine with Switch
type RequestMeta = {
requestId: string;
};
type ApiState =
| ({ status: "idle" } & RequestMeta)
| ({ status: "loading" } & RequestMeta)
| ({ status: "success"; data: string[] } & RequestMeta)
| ({ status: "error"; code: 400 | 404 | 500; message: string } & RequestMeta);
function renderState(state: ApiState): string {
switch (state.status) {
case "idle":
return `[${state.requestId}] Waiting to start...`;
case "loading":
return `[${state.requestId}] Fetching data...`;
case "success":
return `[${state.requestId}] Loaded ${state.data.length} items.`;
case "error":
return `[${state.requestId}] Error ${state.code}: ${state.message}`;
}
}
const currentState: ApiState = {
requestId: "req_884",
status: "success",
data: ["Laptop", "Keyboard", "Mouse"]
};
console.log(renderState(currentState));
Expected output
[req_884] Loaded 3 items.
Step-by-Step Execution Breakdown
RequestMeta, guaranteeing that state.requestId is always available no matter which state we are in.status ("idle", "loading", "success", "error").switch statement, when state.status is "success", TypeScript automatically unlocks state.data. If you try to access state.message there, TypeScript stops you with a compile error.7. Hands-On Practice
Try these exercises in VS Code or the TypeScript Playground to lock in what you learned.
Create a type called TrafficLight that only allows "red", "yellow", or "green". Write a function that takes a TrafficLight and returns what a driver should do.
Hint: Use a switch statement on the literal values.
Create two types: BaseFeature (with name: string and enabled: boolean) and RolloutRule (with percentage: 10 | 25 | 50 | 100). Combine them using an intersection type called FeatureFlag.
Expected result: A valid FeatureFlag object that rejects invalid numbers like 33 for percentage.
Design a Discriminated Union called PaymentState with three states: "pending" (no extra fields), "paid" (includes transactionId: string), and "failed" (includes reason: string). Write a function that prints a receipt or error message based on the state.
Hint: Use a shared status literal property on all three objects.
8. Interview Questions
Senior frontend and full-stack interviews frequently test how well you model domain data using TypeScript's type system.
Answer: A Union (A | B) means a value can be either type A or type B. An Intersection (A & B) means a value must satisfy both type A and type B at the same time, combining all of their properties.
string & number?
Answer: TypeScript evaluates it to the never type. Because no value can simultaneously be a string and a number, it is an impossible type.
Answer: Boolean flags (like isLoading and isError) allow impossible states, such as both being true at once. A Discriminated Union uses a shared literal property (like status) so only one valid state can exist at a time, and TypeScript automatically narrows the available fields for each state.
enum?
Answer: Literal Type unions (like "asc" | "desc") are completely erased when compiled to JavaScript, meaning zero runtime overhead and smaller bundle sizes. They also work cleanly with plain JSON strings from APIs without needing to import an enum object.
Conclusion
Union, Intersection, and Literal types are the backbone of expressive TypeScript. By replacing vague string and boolean flags with exact literals and discriminated unions, you let the compiler catch logic bugs before your users ever see them.
Start applying these patterns to your API responses, configuration objects, and UI states. Your code will become easier to read, safer to refactor, and much more enjoyable to maintain.
Official Documentation
- TypeScript Documentation – Union & Literal Types
- TypeScript Documentation – Intersection Types
- TypeScript Documentation – Discriminated Unions
Upgradix by Shrash Studio – Learn Technology. Build Your Future.