What is the infer keyword in TypeScript?
Answer
The infer keyword is used within conditional types to introduce and capture a type variable that TypeScript deduces from the structure of the type being checked. It can only appear on the right side of an extends clause in a conditional type. Classic example — extracting a function's return type: type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;. TypeScript fills in R with whatever the actual return type is. Extracting the first parameter: type FirstParam<T> = T extends (first: infer F, ...rest: any[]) => any ? F : never;. Unwrapping a Promise: type Awaited<T> = T extends Promise<infer U> ? U : T; (simplified). Extracting array element type: type ElementType<T> = T extends (infer E)[] ? E : never;. infer enables powerful type introspection — extracting parts of complex types without knowing them in advance. It is how TypeScript's built-in ReturnType, Parameters, InstanceType, and Awaited utility types are implemented.
Previous
What are conditional types in TypeScript?
Next
What are template literal types in TypeScript?