Basic Intersection Syntax
You'll learn how to combine multiple types into one using TypeScript's intersection operator.
What Is Intersection Syntax?
An intersection type combines multiple types into a single type that includes all properties from each type. The syntax is simple: you use the & operator between two or more types.
Think of it like a Venn diagram where you want everything from both circles, not just what they share. If TypeA has properties x and y, and TypeB has properties z and w, then TypeA & TypeB has all four properties: x, y, z, and w.
The Syntax
Here's the basic pattern:
type Combined = TypeA & TypeB;
This creates a new type called Combined that requires all properties from both TypeA and TypeB.
A Concrete Example
type Person = {
name: string;
age: number;
};
type Employee = {
employeeId: string;
department: string;
};
type StaffMember = Person & Employee;
const staff: StaffMember = {
name: "Alice",
age: 30,
employeeId: "E123",
department: "Engineering"
};
The StaffMember type now requires all four properties. If you leave any out, TypeScript will give you an error.
Why Use the & Operator?
The & operator lets you build complex types from simpler building blocks. Instead of rewriting all properties in one giant type, you can compose smaller types together, making your code more modular and easier to maintain.
Key Takeaway: Use the & operator between types to create an intersection type that includes all properties from each constituent type—type Combined = TypeA & TypeB merges both types into one.