Extracting Promise Resolved Types
What you'll learn: How to write a conditional type that unwraps Promise<T> using infer to extract what the promise resolves to.
The Problem
When working with promises, you often have a type like Promise<string> or Promise<User>, but you need to extract what's inside the promise — the string or User part. TypeScript provides the Awaited<T> utility for this, but understanding how to build it yourself teaches you powerful infer techniques.
The Solution Pattern
You can create a conditional type that checks if a type is a Promise, and if so, infers and extracts its resolved type:
type UnwrapPromise<T> = T extends Promise<infer U> ? U : T;
Let's break this down:
T extends Promise<infer U>— "Does T match the shape of a Promise of something?"infer U— "If yes, capture that something as a new type variableU"? U— "Return the captured type": T— "Otherwise, just return T unchanged"
How It Works
type A = UnwrapPromise<Promise<string>>; // string
type B = UnwrapPromise<Promise<number>>; // number
type C = UnwrapPromise<string>; // string (not a promise, returned as-is)
Think of infer as a pattern-matching wildcard: "I don't know what type is inside this Promise, but whatever it is, capture it as U so I can use it."
Real-World Use
This pattern is essential when building type-safe async utilities or extracting return types from async functions:
type ExtractResolved<T> = T extends Promise<infer R> ? R : never;
type Result = ExtractResolved<Promise<boolean>>; // boolean
Key Takeaway: Use T extends Promise<infer U> to unwrap promises: the conditional checks the structure, and infer captures the resolved type for extraction.