🔷 TypeScript Intermediate

What is the infer keyword in TypeScript?

Why Interviewers Ask This

This question targets practical, hands-on experience with TypeScript. Interviewers want to see if you've worked with these concepts in real projects, not just read about them. Strong answers include concrete examples.

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.

Common Mistake

Don't just define the term — demonstrate that you understand when to use it and when not to. Showing awareness of trade-offs is what separates average from strong TypeScript candidates.