Extracting Promise Resolution Types
What you'll learn: How to build a type that unwraps the resolved value from a Promise using infer.
When working with asynchronous code, you often encounter Promise<T> types where you need to extract that inner T. TypeScript doesn't give you direct access to the wrapped type, but you can use conditional types with infer to peel away the Promise wrapper and capture what's inside.
The Core Problem
Imagine you have a function that returns Promise<User> and you want to create a type representing just User without manually duplicating it. Or perhaps you're building a generic utility that needs to work with the resolved value of any promise.
The Solution Pattern
You can use a conditional type with infer to extract the resolution type:
type Unwrap<T> = T extends Promise<infer U> ? U : T;
Here's how this works: if T matches the pattern Promise<something>, TypeScript captures that "something" into the type variable U and returns it. If T isn't a Promise at all, it just returns T unchanged.
Real-World Usage
type Unwrap<T> = T extends Promise<infer U> ? U : T;
async function fetchUser() {
return { id: 1, name: "Alice" };
}
type FetchUserReturn = ReturnType<typeof fetchUser>;
// FetchUserReturn is Promise<{ id: number; name: string }>
type User = Unwrap<FetchUserReturn>;
// User is { id: number; name: string }
This pattern is so common that TypeScript includes a built-in utility type called Awaited<T> that does exactly this (and handles nested promises too).
Key Takeaway: Use T extends Promise<infer U> ? U : T to extract the resolved value type from a Promise, leveraging infer to capture the wrapped type for use in the true branch of your conditional type.