Function Type Intersections
What you'll learn: How TypeScript combines function signatures in intersections to create overloaded function types.
The Core Idea
When you intersect two function types, TypeScript doesn't try to merge them into a single signature—instead, it creates a function overload. The resulting type is callable in multiple ways, matching either function signature. Think of it like a Swiss Army knife: one tool that can perform different operations depending on how you use it.
How It Works
type Logger = (message: string) => void;
type Counter = (count: number) => void;
type MultiFunc = Logger & Counter;
// MultiFunc can be called as either Logger OR Counter
const fn: MultiFunc = ((x: string | number) => {
if (typeof x === "string") {
console.log("Message:", x);
} else {
console.log("Count:", x);
}
}) as MultiFunc;
fn("hello"); // Valid: matches Logger
fn(42); // Valid: matches Counter
The implementation signature must be compatible with all intersected signatures. You typically need to handle a union of the parameter types internally, then use a type assertion to satisfy TypeScript.
Why This Matters
Function intersections are useful when combining behaviors from different sources or creating APIs that accept multiple call patterns. You'll see this pattern in library code where a function needs flexible input handling while maintaining type safety.
Key Takeaway: Intersecting function types creates an overloaded function that can be called with any of the intersected signatures, requiring an implementation that handles all cases.