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.
Previous
What is the template literal type key remapping in TypeScript?
Next
How does TypeScript handle circular references in types?
More TypeScript Questions
View all →- Advanced What is structural typing in TypeScript?
- Advanced What are branded types (opaque types) in TypeScript?
- Advanced What is the Variance annotation in TypeScript 4.7?
- Advanced What is the satisfies operator used for in TypeScript?
- Advanced How do you implement a deep partial type in TypeScript?