~/alexsh.blog

$ cat advanced-typescript/03-advanced-infer-patterns-and-positions.md

Advanced Infer Patterns and Positions

February 9, 20261 min readpart 03/20

Difficulty: Advanced. Prerequisites: Conditional types, basic infer usage, function types, variance.

The infer keyword is TypeScript's most powerful type extraction tool, but its behavior changes dramatically based on position (covariant vs contravariant). Mastering advanced infer patterns unlocks the ability to extract types from complex structures and understand why certain patterns produce unions vs intersections.

Key concepts

  • Covariant positions (return types): multiple infers produce unions
  • Contravariant positions (parameters): multiple infers produce intersections
  • Using infer X extends Constraint for constrained inference (TS 4.7+)
  • Inferring in template literal types for string parsing
  • Variadic tuple infer: [...infer Head, infer Last]

Example

codets
// COVARIANT - produces UNION
type Returns<T> = T extends { a: () => infer R } | { b: () => infer R } ? R : never;
type RU = Returns<{ a: () => string } | { b: () => number }>; // string | number

// CONTRAVARIANT - produces INTERSECTION
type Params<T> = T extends { a: (x: infer P) => void } | { b: (x: infer P) => void } ? P : never;
type PI = Params<{ a: (x: { foo: 1 }) => void } | { b: (x: { bar: 2 }) => void }>;
// { foo: 1 } & { bar: 2 }

// CONSTRAINED INFER (TS 4.7+)
type FirstStr<T> = T extends [infer S extends string, ...any[]] ? S : never;
type F = FirstStr<['hi', 42]>; // 'hi'

// VARIADIC TUPLE INFER
type Last<T extends any[]> = T extends [...any[], infer L] ? L : never;
type L = Last<[1, 2, 3]>; // 3

// TEMPLATE LITERAL INFER
type ParseRoute<T> = T extends `/${infer Seg}/${infer Rest}`
  ? [Seg, ...ParseRoute<`/${Rest}`>]
  : T extends `/${infer Seg}` ? [Seg] : [];
type Segments = ParseRoute<'/users/123/posts'>; // ['users', '123', 'posts']

// Real-world: tRPC destructures ProcedureBuilder's 8 generic params with infer

Resources

Practice

Hints

  • Remember: infer in covariant position (return types) produces unions, while in contravariant position (parameters) produces intersections.
  • Use "infer X extends Constraint" to narrow what infer matches.