Covariance and Contravariance with infer
You'll learn: How TypeScript's infer keyword behaves differently when extracting types from covariant positions (like return types) versus contravariant positions (like parameters).
The Core Idea
TypeScript determines variance based on where a type appears in a function signature:
- Covariant position: Return types and properties you read from. These flow out of a function.
- Contravariant position: Function parameters. These flow into a function.
When you use infer to extract types, TypeScript infers unions in covariant positions but intersections in contravariant positions. This happens when the same type variable appears multiple times.
Why This Matters
Imagine you have multiple function signatures with different return types. If you extract the return type (covariant), TypeScript unions them—meaning "it could be any of these." But if you extract parameter types (contravariant), TypeScript intersects them—meaning "it must satisfy all of these."
type ExtractReturn<T> = T extends () => infer R ? R : never;
type MultipleReturns = ExtractReturn<(() => string) | (() => number)>;
// Result: string | number (union in covariant position)
type ExtractParam<T> = T extends (arg: infer P) => any ? P : never;
type MultipleParams = ExtractParam<((x: string) => void) | ((x: number) => void)>;
// Result: string & number (intersection in contravariant position)
// This is never because nothing is both string AND number
The return types become a union because the function could return either type. The parameter types become an intersection because a parameter must be callable with all possible argument types.
Key Takeaway: infer in return types produces unions (covariant), while infer in parameter types produces intersections (contravariant)—reflecting how types flow through functions.