Sub topic 12
Unions and intersections of function types
This chapter covers what happens when you combine function types with | and &. It assumes you know union and intersection types on object types, narrowing, and how function parameters and return types are annotated. It also assumes you have met the idea that a function's parameters are checked in the opposite direction from its return value, a property called contravariance. Each section below explains it again where it matters.
Two operators, two different jobs
A union of functions says "this value is one of these functions, and I don't know which". An intersection of functions says "this value is all of these functions at once". Those two readings lead to opposite call rules:
| Type | Meaning | What you may pass | What you get back | Column |
|---|---|---|---|---|
| `A \ | B` (functions) | Exactly one of them, unknown which | Arguments that satisfy both, so parameters are intersected | The union of the return types |
| `A & B` (functions) | Both at once | Arguments that match any one signature, tried in order | The return type of the first matching signature |
The sections below show why, with code you can paste into a .ts file with strict turned on.
Intersections of functions are overloads
An intersection of function types is the type of a function with several call signatures. This is the same thing TypeScript calls an overloaded function.
type Convert = ((x: string) => number) & ((x: number) => string);
declare const convert: Convert;
const a = convert("42"); // number
const b = convert(42); // stringThe compiler checks the signatures from first to last and uses the first one whose parameters accept your arguments. You can write the same type with overload declarations, which also gives you an implementation to run:
function convert(x: string): number;
function convert(x: number): string;
function convert(x: string | number): number | string {
return typeof x === "string" ? Number(x) : String(x);
}
console.log(convert("42") + 1); // 43
console.log(convert(42) + "!"); // "42!"typeof convert is equivalent to the Convert intersection above. The third signature, the implementation signature, is not part of the type. Callers cannot see it.
Order matters
Because the first match wins, a broad signature placed first hides the narrower ones after it.
type Loose = ((x: unknown) => "unknown") & ((x: string) => "string");
type Precise = ((x: string) => "string") & ((x: unknown) => "unknown");
declare const loose: Loose;
declare const precise: Precise;
const r1 = loose("a"); // "unknown"
const r2 = precise("a"); // "string"
const r3 = precise(1); // "unknown"Loose and Precise contain the same two signatures. They behave differently only because of the order. Put the most specific signature first.
Overloads do not distribute over a union argument
Each call is matched against one signature at a time. If the argument is a union, no single signature accepts it, even when every member of the union has a matching signature.
function convert(x: string): number;
function convert(x: number): string;
function convert(x: string | number): number | string {
return typeof x === "string" ? Number(x) : String(x);
}
declare const input: string | number;
convert(input); // error: No overload matches this call.The fix is to add a signature that accepts the union and returns the union of the results:
function convert(x: string): number;
function convert(x: number): string;
function convert(x: string | number): number | string;
function convert(x: string | number): number | string {
return typeof x === "string" ? Number(x) : String(x);
}
declare const input: string | number;
const result = convert(input); // string | numberThe new signature goes last so the narrow signatures still win when the argument is known.
Unions of functions intersect their parameters
Now the opposite case. Suppose a variable holds either a function that takes a string or a function that takes a number:
type Handler = ((x: string) => number) | ((x: number) => boolean);
declare const handle: Handler;
handle("a"); // error
handle(1); // errorBoth calls fail. The compiler does not know which function it holds, so the argument has to be safe for both. A string is not safe for the function that takes a number, and the reverse is also true. The only value that is both a string and a number is never, so the parameter type becomes string & number, which reduces to never. This is contravariance at work: a union in a return position stays a union, but a union of functions turns the parameter positions into an intersection.
When the parameters are compatible, the call works, and the result is the union of the return types:
type Parse = ((input: string) => number) | ((input: string) => boolean);
declare const parse: Parse;
const value = parse("1"); // number | booleanParameters are combined by position. If the members have different numbers of parameters, the call needs the longer list:
type Log = ((a: string) => void) | ((a: string, b: number) => void);
declare const log: Log;
log("x"); // error: Expected 2 arguments, but got 1.
log("x", 1); // okThe compiler needs b because one of the two possible functions requires it.
Limits of calling a union
TypeScript can call a union of functions only when at most one member has overloads and at most one member is generic. If two members are both generic, the call is an error even when the signatures look compatible. In that case, narrow the value first or write a wrapper that handles each case.
A common trap: looking up a handler by key
The union rule surfaces in everyday code when you store handlers in an object and pick one with a key.
type Events = { click: { x: number }; key: { code: string } };
type Handlers = { [K in keyof Events]: (event: Events[K]) => void };
function dispatchBad(
handlers: Handlers,
name: keyof Events,
event: Events[keyof Events],
): void {
handlers[name](event); // error
}handlers[name] has the type ((event: { x: number }) => void) | ((event: { code: string }) => void). Its parameter is { x: number } & { code: string }, and event is only the union of the two. The compiler cannot see that name and event belong together.
Make the key a type parameter. Then handlers[name] has the type Handlers[K], and the compiler can match it to Events[K]:
type Events = { click: { x: number }; key: { code: string } };
type Handlers = { [K in keyof Events]: (event: Events[K]) => void };
function dispatch<K extends keyof Events>(
handlers: Handlers,
name: K,
event: Events[K],
): void {
handlers[name](event);
}
const handlers: Handlers = {
click: (e) => console.log("click at", e.x),
key: (e) => console.log("key", e.code),
};
dispatch(handlers, "click", { x: 10 });
dispatch(handlers, "key", { code: "Enter" });
// dispatch(handlers, "click", { code: "Enter" }); // errorThis pattern is the standard way to keep a key and its payload correlated. It needs a mapped type for Handlers. A hand-written object type with the same members would not work the same way.
Extracting types from function unions and intersections
The built-in helper types Parameters and ReturnType behave differently on the two kinds of type.
type Handler = ((x: string) => number) | ((x: number) => boolean);
type HandlerParams = Parameters<Handler>;
// [x: string] | [x: number]
type HandlerReturn = ReturnType<Handler>;
// number | booleanOn a union, both helpers are conditional types that distribute over the members, so you get a union of the results. (The next chapters in this series cover distribution in detail.)
On an overloaded function, inference looks only at the last signature:
function convert(x: string): number;
function convert(x: number): string;
function convert(x: string | number): number | string {
return typeof x === "string" ? Number(x) : String(x);
}
type ConvertParams = Parameters<typeof convert>; // [x: number]
type ConvertReturn = ReturnType<typeof convert>; // stringThe helpers silently ignore the string overload. If you need all of the signatures, you have to write the types out by hand or restructure the code so the overloads come from a union or a mapped type.
Union of functions versus function of a union
A function that accepts a union is a different type from a union of functions, and the difference shows up in how you can use each one.
type TakesEither = (x: string | number) => void;
type EitherFunction = ((x: string) => void) | ((x: number) => void);
declare const takesEither: TakesEither;
declare const eitherFunction: EitherFunction;
takesEither("a"); // ok
takesEither(1); // ok
eitherFunction("a"); // error: argument must be string & numberYou can assign a TakesEither to an EitherFunction variable, because it can stand in for either member. You cannot assign in the other direction. If you want callers to pass either kind of argument, declare the parameter as a union (x: string | number), or use overloads. A union of functions is the right type only when you receive a function whose exact kind you do not control.
When to use which
- Use an intersection of function types, or overload declarations, when one function should return different types for different argument types, and you can list the cases.
- Use a generic with a conditional return type instead when the relationship between input and output follows a rule rather than a fixed list.
- Use a union of functions rarely, and mostly when a library hands you one. Expect to call it with
never-shaped parameters unless the members share their parameters. - When you pick a function from an object by key, use a generic key plus a mapped type, as in
dispatch.
Exercise
Given type F = ((a: string) => number) | ((a: string | number) => boolean), what is the type of the parameter when you call a value of type F, and what does the call return?
Show answer
The parameter types are intersected: string & (string | number), which simplifies to string. So you can call it with a string. The return type is the union of the two return types, number | boolean.
Exercise
You write type G = ((x: unknown) => "any") & ((x: string) => "text") and call g("hi"). What does it return, and how do you change the type so that it returns "text"?
Show answer
It returns "any", because the first signature (x: unknown) => "any" accepts a string and the compiler uses the first match. Swap the order so the string signature comes first: ((x: string) => "text") & ((x: unknown) => "any").
Exercise
Why does handlers[name](event) fail when name has the type keyof Events, and what two changes make it compile?
Show answer
handlers[name] is a union of handler functions, so its parameter is the intersection of every event type, and a plain union of events does not satisfy it. Make the key a type parameter K extends keyof Events, type the event as Events[K], and define Handlers as a mapped type over keyof Events, so the compiler can link Handlers[K] to Events[K].