Advertisement
Intermediate TypeScript, Conditional Types

What does the 'infer' keyword do inside a conditional type?

Short answer

infer introduces a new type variable within the 'extends' clause of a conditional type, letting TypeScript capture and name a piece of the matched type structure for use in the true branch — essentially pattern-matching on types.

Save TypeScript mock interview
Advertisement
AModel answer
infer introduces a new type variable within the 'extends' clause of a conditional type, letting TypeScript capture and name a piece of the matched type structure for use in the true branch — essentially pattern-matching on types.
type ReturnTypeOf<T> = T extends (...args: any[]) => infer R ? R : never;
type A = ReturnTypeOf<() => string>; // string
Real-world example
Extracting a function's return type automatically, which is exactly how TypeScript's built-in ReturnType<T> utility type works.
Likely follow-ups
  • Can you use infer more than once within the same conditional type?
Related topics