Intermediate LevelJavaScript & TypeScript
What is the infer keyword in TypeScript conditional types?
❓ Interview Prompt: Explain type inference within conditional types using infer to unwrap Promises, functions, and arrays.
The `infer` keyword can only be used inside the true/extends condition of a conditional type to declare a temporary type variable that TypeScript automatically infers from surrounding structure.
Use Cases:
•
Extracting return types from functions (
ReturnType<T>).•
Unwrapping resolved Promise values (
Awaited<T>).•
Extracting array element types (
UnpackArray<T>).Code Implementation Example
typescript
// Custom ReturnType using infer
type MyReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
function getUser() {
return { id: 1, name: 'Alice' };
}
type UserResult = MyReturnType<typeof getUser>; // { id: number; name: string; }
// Unwrapping Promise inner type using infer
type UnwrapPromise<T> = T extends Promise<infer U> ? U : T;
type AsyncData = Promise<number[]>;
type ResolvedData = UnwrapPromise<AsyncData>; // number[]💡Extracting function return types and unwrapping Promise generic types using infer.
🎯 Interview Key Takeaway
Use infer within conditional types to extract and unwrap nested type variables like Promise return types.
#TypeScript#infer#Conditional Types#Intermediate
Back to all JavaScript & TypeScript Questions→