TypeScript
/Advanced
infer Keyword
Definition
Used strictly within Conditional Types to declare a new local type variable that TypeScript will automatically deduce (infer) during compilation.
Explain Like I'm New
The `infer` keyword is a detective. You give TS a complex type (like an Array of Promises containing Strings) and say: 'I know this is a Promise. Please *infer* what type is buried inside the Promise, save it to a variable, and give it back to me.'
Real World Example
The native `ReturnType<T>` utility. It inspects a function type, uses `infer` to figure out what the function returns, and hands that exact type back to you.
Common Use Cases
- •Extracting return types of functions
- •Extracting values from Promises
- •Advanced utility types
Interactive Example
// A custom utility to extract what's inside an Array // Logic: If T is an Array containing SOME type (infer U), return U. Otherwise, return T. type UnpackArray<T> = T extends Array<infer U> ? U : T; type A = UnpackArray<string[]>; // TS infers U is string. Returns: string type B = UnpackArray<number>; // Not an array. Returns: number // How the built-in ReturnType works: // If T is a function returning SOME type (infer R), return R. type MyReturnType<T> = T extends (...args: any[]) => infer R ? R : never; type Func = () => boolean; type Ret = MyReturnType<Func>; // Evaluates to: boolean
Interview Questions
basic
- Where is the ONLY place you can use the `infer` keyword?
intermediate
- How do you write a type that unwraps an Array type into its inner item type?
advanced
- Can you use multiple `infer` declarations in a single condition?