Generic Promise Wrappers
What you'll learn: How to write type-safe functions that wrap values in Promises while preserving exact type information through async operations.
Why Promise Wrappers Need Generics
When you create utility functions that return Promises, you want TypeScript to track what type of value the Promise will eventually resolve to. Without generics, you'd lose that information and get back Promise<any> or Promise<unknown>.
Generic Promise wrappers let you take any value of type T and return Promise<T>, maintaining full type safety across the async boundary.
The Basic Pattern
function asyncWrap<T>(value: T): Promise<T> {
return Promise.resolve(value);
}
// TypeScript knows this is Promise<number>
const num = asyncWrap(42);
// TypeScript knows this is Promise<string>
const str = asyncWrap("hello");
// TypeScript knows this is Promise<User>
const user = asyncWrap({ id: 1, name: "Alice" });
The type parameter T captures whatever type you pass in, then wraps it in Promise<T>.
Real-World Use Cases
Delayed resolution:
function delay<T>(ms: number, value: T): Promise<T> {
return new Promise(resolve =>
setTimeout(() => resolve(value), ms)
);
}
// Type: Promise<boolean>
delay(1000, true);
Error-safe wrappers:
function safe<T>(value: T): Promise<{ success: true; data: T }> {
return Promise.resolve({ success: true, data: value });
}
How This Relates to Constraints
You learned constraints earlier — you can require that T has specific properties while still preserving the exact type through the Promise wrapper.
Key takeaway: Generic Promise wrappers use type parameters to preserve exact value types across async boundaries, giving you full autocomplete and type safety when the Promise resolves.