Practical infer Use Cases: Unwrapping Promises
Unwrap Promise, Array, and custom wrapper types.
The Unwrapping Problem
When working with async code, you often receive Promise and need the underlying T. The infer keyword makes this extraction reusable.
type Awaited<T> = T extends Promise<infer U> ? U : T;
type A = Awaited<Promise<string>>; // string
type B = Awaited<number>; // numberBuilt-in Awaited Utility
TypeScript 4.5 introduced the built-in Awaited that handles nested promises recursively.
type A = Awaited<Promise<Promise<string>>>; // string
// Handles arbitrary nesting automaticallyAll lessons in this course
- Understanding infer in Conditional Types
- Building ReturnType and Parameters from Scratch
- Deeply Nested Inference Patterns
- Practical infer Use Cases: Unwrapping Promises