What is the infer keyword with conditional types in depth?

Answer

The infer keyword inside conditional types introduces a type variable that TypeScript fills in by pattern matching on the type structure. It enables extracting parts of a type. Multiple infers: you can use multiple infer in one condition: type Head<T extends any[]> = T extends [infer H, ...any[]] ? H : never; — extracts the first element of a tuple. type Tail<T extends any[]> = T extends [any, ...infer T] ? T : never; — all but the first. Infer in co/contravariant positions: in covariant positions (return type), multiple infers for the same variable produce a union. In contravariant positions (function parameters), they produce an intersection. Infer for deeply nested: type UnpackPromise<T> = T extends Promise<infer U> ? UnpackPromise<U> : T; — recursively unwraps nested promises. TypeScript 4.7 added the ability to use infer with variance annotations: infer T extends string — constrains the inferred type.