Course contentsShow
← TypeScript
Lesson 1444 of 1,79633. Inference Inversion PatternsFree lesson

Covariance and Contravariance with infer

Understanding how infer behaves differently in covariant vs contravariant positions like return types vs parameters.

Covariance and Contravariance with infer

You'll learn how infer behaves differently depending on whether it appears in a covariant position (like return types) or contravariant position (like parameters).

What This Means

When TypeScript infers a type using infer, it doesn't always work the same way. The position where infer appears changes how TypeScript combines multiple possibilities:

  • Covariant position (return types, property types): TypeScript creates a union of all possibilities
  • Contravariant position (function parameters): TypeScript creates an intersection of all possibilities

Think of it like this: When returning values (covariant), TypeScript says "it could be any of these types." When accepting parameters (contravariant), TypeScript says "it must satisfy all of these types."

Covariant Behavior: Returns Create Unions

type ReturnTypes<T> = T extends (...args: any[]) => infer R ? R : never;

type Example1 = ReturnTypes<() => string | (() => number)>;
// Result: string | number
// The inferred R becomes a union

When infer R appears in the return position, multiple function types yield a union.

Contravariant Behavior: Parameters Create Intersections

type ParamTypes<T> = T extends (arg: infer P) => any ? P : never;

type Example2 = ParamTypes<((x: string) => void) | ((x: number) => void)>;
// Result: string & number (which resolves to never)
// The inferred P becomes an intersection

In parameter position, TypeScript creates an intersection because a function accepting the parameter must handle all types.

Why This Matters

This variance behavior explains surprising type inference results. Covariant infer is permissive (union), while contravariant infer is restrictive (intersection).

Key Takeaway: infer in return positions creates unions (covariant), while infer in parameter positions creates intersections (contravariant) — the position determines how TypeScript combines multiple inferred types.