What is the infer keyword with conditional types in depth?

Why Interviewers Ask This

Interviewers ask this to evaluate whether you have the depth of knowledge needed to mentor others and lead technical decisions. The expected answer goes beyond definitions into practical implications and real-world consequences.

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.

Common Mistake

Candidates often give textbook answers here. Interviewers are more impressed when you relate the concept to a specific problem you solved in a real TypeScript project.