Mixin Pattern with Intersections
You'll learn how to compose objects with multiple capabilities by intersecting a base type with behavior-providing types—a technique called the mixin pattern.
What Are Mixins?
Imagine building a character in a video game. You start with a base character type, then mix in abilities like "can fly," "can swim," or "can shoot lasers." Each ability is independent, and you compose them together to create the final character. In TypeScript, intersection types let you implement this mixin pattern by combining a base type with multiple behavior types.
The Core Pattern
A mixin combines a base type with one or more capability types using the & operator. Each capability type adds specific properties or methods to the base:
type Entity = {
id: number;
name: string;
};
type Flyable = {
altitude: number;
fly: () => void;
};
type Swimmable = {
depth: number;
swim: () => void;
};
// Mix capabilities into the base type
type FlyingFish = Entity & Flyable & Swimmable;
const nemo: FlyingFish = {
id: 1,
name: "Nemo",
altitude: 0,
fly: () => console.log("Soaring!"),
depth: 20,
swim: () => console.log("Swimming!")
};
Each mixin (Flyable, Swimmable) represents a discrete capability. The intersection creates a type with all properties from all types—no capability is lost.
When to Use This Pattern
Use mixins when you want to compose behavior without deep inheritance hierarchies. They're perfect for cross-cutting concerns like logging, timestamps, or permissions that apply to many different base types.
Key Takeaway: The mixin pattern uses intersection types to compose a base type with multiple behavior-providing types, creating flexible, reusable capability combinations without inheritance.