Series: TypeScript from Basics to Advanced
Part: 6 — Union & Intersection Types
Level: Beginner → Intermediate
Introduction
In the previous part, we learned about Type Aliases and Interfaces and how they help us create reusable types.
But real-world applications often have data that can be one of several possible types or data that needs to combine multiple types.
For example:
-
A user ID might be a
stringor anumber. -
An API response might represent either success or failure.
-
A payment status might be
"pending","success", or"failed". -
A user might be either an admin or a normal user.
-
An object might need to contain properties from multiple different types.
This is where Union Types and Intersection Types become extremely useful.
In this article, we'll learn:
-
What Union Types are
-
The
|operator -
Literal Union Types
-
Union Types with objects
-
Discriminated Unions
-
What Intersection Types are
-
The
&operator -
Combining interfaces and types
-
Union vs Intersection
-
Real-world examples
-
Common mistakes
-
Best practices
1. What Is a Union Type?
A Union Type allows a value to be one of multiple types.
We create a union using the | operator.
let id: string | number;
id = "USR001";
id = 1001;
The variable id can contain either:
string OR number
That's why we use:
string | number
Think of the | symbol as OR.
string | number
↓
string OR number
2. Basic Union Type Examples
String or number
let value: string | number;
value = "Hello";
value = 100;
Both are valid.
But this is invalid:
value = true;
TypeScript will show an error because boolean isn't part of the union.
String or null
Union types are also useful when a value can be missing.
let username: string | null;
username = "Sundar";
username = null;
This is common when working with databases and APIs.
For example:
let loggedInUser: User | null;
This means:
loggedInUser can be a User
OR
loggedInUser can be null
3. Union Types in Function Parameters
Union types are particularly useful for functions.
function printId(id: string | number) {
console.log(id);
}
printId("USR001");
printId(1001);
Both calls are valid.
This is useful when an API accepts multiple formats.
function getUser(id: string | number) {
// fetch user
}
Now the function accepts:
getUser("USR001");
getUser(1001);
4. Union Types and Type Narrowing
When TypeScript sees:
function printId(id: string | number) {
console.log(id);
}
TypeScript doesn't know whether id is currently a string or a number.
If we want to use type-specific functionality, we need to narrow the type.
function printId(id: string | number) {
if (typeof id === "string") {
console.log(id.toUpperCase());
} else {
console.log(id.toFixed(2));
}
}
Here:
typeof id === "string"
tells TypeScript that inside this block, id is a string.
We'll explore this in much more detail in Part 7: Type Narrowing & Type Guards.
5. Literal Union Types
Union types become even more powerful when combined with literal types.
Instead of allowing any string:
let status: string;
we can restrict the possible values:
let status: "pending" | "success" | "failed";
Only these values are allowed:
status = "pending";
status = "success";
status = "failed";
This is invalid:
status = "completed";
because "completed" isn't part of the union.
6. Why Literal Unions Are Useful
Suppose you're building an online test application.
A test can have these statuses:
type TestStatus =
| "not-started"
| "in-progress"
| "completed";
Now:
let testStatus: TestStatus;
testStatus = "not-started";
testStatus = "in-progress";
testStatus = "completed";
But:
testStatus = "finished";
will produce an error.
This prevents accidental values from entering your application.
7. Union Types with Arrays
You can create an array containing multiple types.
let values: (string | number)[];
values = ["Sundar", 10, "TypeScript", 20];
Every element must be either:
string OR number
Another example:
const data: (string | boolean)[] = [
"Hello",
true,
"World",
false
];
Important: Parentheses
Be careful with:
let values: string | number[];
This means:
string OR array of numbers
It does not mean an array containing strings or numbers.
For that, use:
let values: (string | number)[];
8. Union Types with Object Types
Union types can represent different object shapes.
type Admin = {
name: string;
permissions: string[];
};
type User = {
name: string;
email: string;
};
type Account = Admin | User;
Now Account can represent either an Admin or a User.
For example:
const account: Account = {
name: "Sundar",
email: "sundar@example.com"
};
or:
const account: Account = {
name: "Admin",
permissions: ["read", "write"]
};
9. The Problem with Object Unions
When working with object unions, TypeScript only allows you to directly access properties that are common to all members.
For example:
function printName(account: Account) {
console.log(account.name);
}
This works because both Admin and User have name.
But this isn't automatically safe:
function printAccount(account: Account) {
console.log(account.email);
}
An Admin doesn't necessarily have an email.
We need to determine which type we're dealing with first.
10. Discriminated Unions
One of the most useful patterns in TypeScript is the Discriminated Union.
We add a common property that tells us which type we're dealing with.
type Admin = {
role: "admin";
name: string;
permissions: string[];
};
type User = {
role: "user";
name: string;
email: string;
};
type Account = Admin | User;
Now we can check the role:
function printAccount(account: Account) {
if (account.role === "admin") {
console.log(account.permissions);
} else {
console.log(account.email);
}
}
TypeScript automatically understands the correct type inside each branch.
This pattern is extremely useful for:
-
API responses
-
Redux state
-
React components
-
Payment states
-
Authentication
-
Form states
-
Application state machines
11. Real-World API Example
Suppose your backend returns either a successful response or an error.
We can model that using a union:
type SuccessResponse = {
status: "success";
data: User;
};
type ErrorResponse = {
status: "error";
message: string;
};
type ApiResponse = SuccessResponse | ErrorResponse;
Now:
function handleResponse(response: ApiResponse) {
if (response.status === "success") {
console.log(response.data);
} else {
console.log(response.message);
}
}
This is safer than:
type ApiResponse = {
status: string;
data?: User;
message?: string;
};
The union describes the valid states more accurately.
12. Real-World Online Test Example
Imagine your online test application has three states:
type TestState =
| {
status: "not-started";
}
| {
status: "in-progress";
questionNumber: number;
}
| {
status: "completed";
score: number;
};
Now:
function showTestState(state: TestState) {
switch (state.status) {
case "not-started":
console.log("Start the test");
break;
case "in-progress":
console.log(`Question ${state.questionNumber}`);
break;
case "completed":
console.log(`Score: ${state.score}`);
break;
}
}
Each state has exactly the properties it needs.
13. What Is an Intersection Type?
An Intersection Type combines multiple types into one.
We create an intersection using the & operator.
Think of & as:
AND
For example:
type Person = {
name: string;
};
type Employee = {
employeeId: number;
};
type EmployeePerson = Person & Employee;
EmployeePerson must contain properties from both types.
const employee: EmployeePerson = {
name: "Sundar",
employeeId: 1001
};
14. Union vs Intersection
This is one of the most important concepts to remember.
Union
type A = Type1 | Type2;
Means:
Type1 OR Type2
Intersection
type A = Type1 & Type2;
Means:
Type1 AND Type2
A simple way to remember:
OperatorMeaningExample|ORstring | number&ANDUser & Employee
15. Intersection with Interfaces
Intersection types work nicely with interfaces.
interface User {
name: string;
email: string;
}
interface Employee {
employeeId: number;
department: string;
}
type EmployeeUser = User & Employee;
Now:
const employee: EmployeeUser = {
name: "Sundar",
email: "sundar@example.com",
employeeId: 101,
department: "Engineering"
};
The object must satisfy both interfaces.
16. Extending vs Intersection
There are two common ways to combine types.
Using interface extension:
interface User {
name: string;
}
interface Employee extends User {
employeeId: number;
}
Or using an intersection:
type User = {
name: string;
};
type Employee = User & {
employeeId: number;
};
Both can produce similar results.
The choice depends on your design and whether you're working primarily with interfaces or type aliases.
17. Combining Multiple Types
You can intersect more than two types.
type User = {
name: string;
};
type Employee = {
employeeId: number;
};
type Developer = {
programmingLanguages: string[];
};
type DeveloperEmployee = User & Employee & Developer;
Now:
const developer: DeveloperEmployee = {
name: "Sundar",
employeeId: 101,
programmingLanguages: [
"JavaScript",
"TypeScript",
"React"
]
};
The object must satisfy all three types.
18. Intersection Types and Conflicting Properties
There is an important caveat with intersections.
Consider:
type A = {
id: string;
};
type B = {
id: number;
};
type C = A & B;
The id property would need to satisfy both:
string AND number
There is no ordinary value that can satisfy both types.
As a result, the intersection becomes effectively impossible to construct.
So be careful when combining types that contain properties with incompatible types.
19. Practical Payment Example
Imagine a payment system.
Different payment methods can be represented using a union:
type CardPayment = {
method: "card";
cardNumber: string;
};
type UpiPayment = {
method: "upi";
upiId: string;
};
type Payment = CardPayment | UpiPayment;
A payment is either:
CardPayment OR UpiPayment
Now suppose every payment also needs common transaction information:
type Transaction = {
transactionId: string;
amount: number;
};
We can combine them:
type CardTransaction = CardPayment & Transaction;
type UpiTransaction = UpiPayment & Transaction;
type PaymentTransaction =
| CardTransaction
| UpiTransaction;
Here we are using both concepts:
-
Union → different possible payment methods
-
Intersection → combine payment information with transaction information
20. Union Types in React
Union types are very common in React applications.
For example, a button may support multiple variants:
type ButtonVariant =
| "primary"
| "secondary"
| "danger";
Then:
interface ButtonProps {
text: string;
variant: ButtonVariant;
}
A component can receive:
<Button text="Save" variant="primary" />
or:
<Button text="Delete" variant="danger" />
But this is invalid:
<Button text="Save" variant="success" />
This is much safer than:
variant: string;
21. Union Types for Conditional Props
Sometimes different props should exist depending on another prop.
For example:
type ButtonProps =
| {
type: "link";
href: string;
}
| {
type: "button";
onClick: () => void;
};
Now:
const linkButton: ButtonProps = {
type: "link",
href: "/home"
};
And:
const normalButton: ButtonProps = {
type: "button",
onClick: () => {
console.log("Clicked");
}
};
The union describes the valid combinations.
22. Union Types with null
A very common application pattern is:
let user: User | null = null;
Initially:
user = null;
After login:
user = {
id: 1,
name: "Sundar"
};
TypeScript understands that the value can be either:
User OR null
This is especially useful for authentication state.
23. Union Types vs any
Consider:
let data: any;
This disables much of TypeScript's type checking.
Instead:
let data: string | number;
is much safer when you know the possible types.
For example:
function processValue(value: string | number) {
if (typeof value === "string") {
return value.toUpperCase();
}
return value * 2;
}
TypeScript can help ensure that both possibilities are handled correctly.
24. Exhaustive Checking
Discriminated unions can also help ensure that every possible state is handled.
type Status =
| "pending"
| "success"
| "failed";
We can use:
function handleStatus(status: Status) {
switch (status) {
case "pending":
return "Waiting";
case "success":
return "Completed";
case "failed":
return "Failed";
}
}
We can also use never for exhaustive checking:
function assertNever(value: never): never {
throw new Error(`Unexpected value: ${value}`);
}
Then:
function handleStatus(status: Status) {
switch (status) {
case "pending":
return "Waiting";
case "success":
return "Completed";
case "failed":
return "Failed";
default:
return assertNever(status);
}
}
If a new status is added later but not handled, TypeScript can identify the problem.
25. Common Mistakes
Mistake 1: Confusing | and &
Remember:
string | number
means:
string OR number
while:
TypeA & TypeB
means:
TypeA AND TypeB
Mistake 2: Forgetting parentheses in arrays
Incorrect:
string | number[];
Correct:
(string | number)[];
Mistake 3: Using string instead of literal unions
Instead of:
type Status = string;
when the possible values are known, prefer:
type Status =
| "pending"
| "success"
| "failed";
Mistake 4: Making everything optional
Instead of:
interface Response {
success: boolean;
data?: User;
error?: string;
}
consider:
type Response =
| {
success: true;
data: User;
}
| {
success: false;
error: string;
};
This makes invalid states harder to represent.
Mistake 5: Creating conflicting intersections
Be careful with:
type A = {
id: string;
};
type B = {
id: number;
};
type C = A & B;
Conflicting property types can make the resulting type impossible to construct.
26. When Should You Use Union Types?
Use a union when a value can legitimately have different possible types or states.
Common examples:
string | number
User | null
"pending" | "success" | "failed"
Admin | User
SuccessResponse | ErrorResponse
27. When Should You Use Intersection Types?
Use an intersection when an entity needs to satisfy multiple type definitions simultaneously.
For example:
type User = {
name: string;
};
type Employee = {
employeeId: number;
};
type EmployeeUser = User & Employee;
Common use cases include:
-
Combining object types
-
Composing reusable types
-
Adding common properties
-
Building complex domain models
-
Combining library-provided types with application-specific types
28. A Simple Mental Model
The easiest way to remember these concepts is:
Union
It can be this OR that.
type ID = string | number;
An ID can be a string or number.
Intersection
It must be this AND that.
type EmployeeUser = User & Employee;
An employee user must satisfy both User and Employee.
29. Best Practices
1. Prefer literal unions for fixed values
type Role = "admin" | "user" | "moderator";
instead of:
type Role = string;
2. Use discriminated unions for different states
type State =
| { status: "loading" }
| { status: "success"; data: User }
| { status: "error"; message: string };
3. Use unions instead of any when possible
string | number
is much safer than:
any
4. Use intersections to compose compatible object types
type EmployeeUser = User & Employee;
5. Avoid conflicting properties in intersections
Make sure combined types are logically compatible.
6. Use meaningful discriminators
Good examples include:
status: "success"
type: "card"
role: "admin"
These make type narrowing predictable and readable.
Final Takeaway
Union and intersection types are two of the most important tools for modeling complex data in TypeScript.
The key difference is simple:
A | B
means:
A OR B
while:
A & B
means:
A AND B
Union types are especially useful for:
-
Multiple possible values
-
Literal values
-
API responses
-
Application states
-
React props
-
Authentication states
Intersection types are useful for:
-
Combining object types
-
Composing reusable models
-
Adding multiple sets of properties to one object
Once you understand these two operators, TypeScript becomes much more expressive because you can describe not just what data looks like, but also what states are actually valid.