Sub topic 6
Multiple candidates: unions, intersections and UnionToIntersection
Earlier chapters used infer to capture one piece of a type. This chapter covers what happens when the same infer variable is captured in several places, or from several union members. The result is sometimes a union and sometimes an intersection, and the position of each capture decides which.
This chapter assumes you can read conditional types and basic infer patterns, and that you know how distribution over unions works. You should also know what a function parameter type is and how A & B behaves for object types.
One name, several candidates
If you write infer U once, the compiler collects one candidate for U. If the same name appears at several places in the pattern, each place contributes a candidate. The compiler then has to combine them into a single type.
The combination rule depends on where each candidate came from:
- A candidate from a position where the type is produced or read is covariant. Examples are property types, array elements and return types.
- A candidate from a position where the type is consumed is contravariant. The main example is a function parameter.
| Position of the candidates | Variance | Combined result |
|---|---|---|
| Property types, array elements, return types | Covariant | Union of the candidates |
| Function parameter types | Contravariant | Intersection of the candidates |
Covariant candidates produce a union
Here the same U is captured from two properties:
type PropTypes<T> = T extends { a: infer U; b: infer U } ? U : never;
type P1 = PropTypes<{ a: string; b: number }>; // string | number
type P2 = PropTypes<{ a: boolean; b: boolean }>; // booleanBoth candidates are covariant, so the compiler unions them. In P2 the two identical candidates collapse to one boolean.
The same thing happens with tuples. A tuple has one candidate per element, and the array pattern (infer U)[] collects all of them:
type ElementOf<T> = T extends (infer U)[] ? U : never;
type E1 = ElementOf<[string, number, boolean]>; // string | number | boolean
type E2 = ElementOf<string[]>; // stringElementOf<[string, number, boolean]> is why T[number] and (infer U)[] give you the "all element types" union for a tuple.
Contravariant candidates produce an intersection
Now put U in parameter positions:
type ParamsOf<T> = T extends {
a: (x: infer U) => void;
b: (x: infer U) => void;
}
? U
: never;
type Q = ParamsOf<{
a: (x: { p: 1 }) => void;
b: (x: { q: 2 }) => void;
}>;
// { p: 1 } & { q: 2 }The reasoning is about safety. The matched type has two functions that accept different arguments. A value that can be passed to both must satisfy both parameter types, so the only safe U is the intersection { p: 1 } & { q: 2 }. A union would be unsafe, because a { p: 1 } value is not acceptable to the function that wants { q: 2 }.
Building UnionToIntersection
The two rules combine into a well-known utility. A union such as A | B has no parameter positions, so there is nothing to infer contravariantly. The trick is to turn each union member into a function parameter, then infer from those parameters:
type UnionToIntersection<U> =
(U extends unknown ? (arg: U) => void : never) extends (arg: infer I) => void
? I
: never;
type Merged = UnionToIntersection<{ a: 1 } | { b: 2 }>;
// { a: 1 } & { b: 2 }It runs in three steps.
- Distribute.
U extends unknown ? ... : neveris a distributive conditional, becauseUis a naked type parameter. Each member becomes its own function, so the result is((arg: { a: 1 }) => void) | ((arg: { b: 2 }) => void). - Match. That union of functions is the checked type of the outer
extends. Each function is compared against(arg: infer I) => void. The outer check is not distributive, because its checked type is a compound expression and not a naked type parameter. - Combine.
Iis in a parameter position, so each function contributes a contravariant candidate. The compiler intersects them:{ a: 1 } & { b: 2 }.
Why the distribution step matters
The U extends unknown ? wrapper looks redundant, but removing it changes the answer:
type Broken<U> =
((arg: U) => void) extends (arg: infer I) => void ? I : never;
type B1 = Broken<{ a: 1 } | { b: 2 }>; // { a: 1 } | { b: 2 }Without distribution there is a single function whose parameter is the whole union. It gives one candidate, the union itself, so nothing is intersected. The wrapper exists only to split the union into separate functions before the contravariant inference.
A practical use
Intersecting a union is useful when each union member describes one capability and you want the combined type. This example builds the API type of an app from a list of feature descriptors:
type Feature =
| { id: 'cache'; api: { clear(): void } }
| { id: 'log'; api: { log(message: string): void } };
type UnionToIntersection<U> =
(U extends unknown ? (arg: U) => void : never) extends (arg: infer I) => void
? I
: never;
type CombinedApi = UnionToIntersection<Feature['api']>;
// { clear(): void } & { log(message: string): void }
declare const api: CombinedApi;
api.clear();
api.log('started');Feature['api'] is itself a union of the two api object types. The utility merges it into one type with both methods. Both calls type-check.
Gotchas and failure modes
Primitives and conflicting members collapse to never
An intersection of incompatible types is never:
type UnionToIntersection<U> =
(U extends unknown ? (arg: U) => void : never) extends (arg: infer I) => void
? I
: never;
type N1 = UnionToIntersection<string | number>; // never
type N2 = UnionToIntersection<boolean>; // neverboolean is the union true | false, so it is distributed into two members and true & false is never. Object members whose properties have different literal types, such as { kind: 'a' } | { kind: 'b' }, also reduce to never, because the shared kind property becomes 'a' & 'b'.
The result depends on strictFunctionTypes
Contravariant inference from parameters happens only when strictFunctionTypes is on. strict: true in tsconfig.json turns it on. With the flag off, the compiler treats parameter positions as bivariant for inference, so UnionToIntersection quietly returns a union. If this utility "does nothing" in a project, check that flag first.
Mixed positions are hard to predict
If one infer variable appears in both a covariant and a contravariant position, the compiler usually prefers the covariant candidates when they fit the contravariant ones. Otherwise it falls back to the contravariant ones. The exact outcome is an implementation detail. If you need such a pattern, test it with a compile-time assertion (covered in a later chapter) and don't rely on memory.
Union order is not a contract
A union has no defined order. Utilities that pull a "last member" out of a union, by intersecting functions into an overload set and inferring from it, rely on how the compiler happens to order the union. A change of compiler version or an unrelated edit elsewhere can change the order. Don't build behavior you care about on it.
Decision criteria
- Use several
infer Ucaptures in covariant positions when you want "any of these". The union is what you want. - Use captures in parameter positions when you want "something satisfying all of these". The intersection is what you want.
- Use
UnionToIntersectionwhen you start from a union and need a merged type. Check that the members are object types that don't conflict. - If you control the type, consider writing the intersection or an object map directly. This utility is for cases where the union already exists, for example when it comes from a library.
Exercise
What are the results of UnionToIntersection<string | number> and of PropTypes<{ a: 1; b: 2 }>, where PropTypes<T> = T extends { a: infer U; b: infer U } ? U : never? Explain why the two behave differently.
Show answer
UnionToIntersection<string | number> is never, because the parameter positions give contravariant candidates string and number, and string & number is never. PropTypes<{ a: 1; b: 2 }> is 1 | 2, because the candidates come from property types, which are covariant positions, so the compiler unions them.
Exercise
A teammate says UnionToIntersection<{ a: 1 } | { b: 2 }> returns { a: 1 } | { b: 2 } in their project, although the code is copied exactly. Name the most likely cause and the fix.
Show answer
strictFunctionTypes is probably off, so parameter positions are not inferred contravariantly and the candidates are unioned. Enable it, for example with "strict": true in tsconfig.json, or set "strictFunctionTypes": true.
Exercise
Write a type Handlers<T> that, given { a: (x: infer U) => void; b: (x: infer U) => void } style input, returns the single argument type accepted by both a and b. Then give the result for { a: (x: { p: 1 }) => void; b: (x: { q: 2 }) => void }.
Show answer
type Handlers<T> = T extends { a: (x: infer U) => void; b: (x: infer U) => void } ? U : never; The result for the given input is { p: 1 } & { q: 2 }, because both candidates come from parameter positions and are intersected.