Promise-Based API Generics
What you'll learn: How TypeScript uses generics to type the eventual resolved value inside Promises.
The Core Idea
When you work with asynchronous code in TypeScript, Promise is a generic type that wraps the eventual value. Think of a Promise like a gift box: the box itself is always a Promise, but what's inside—the gift—can be any type. Generics let you specify what's in that box.
The syntax is Promise<T>, where T is the type of the resolved value. When you await or .then() that Promise, TypeScript knows what type you'll get back.
How It Works
// A function returning a Promise of a number
async function fetchAge(): Promise<number> {
return 25;
}
// A function returning a Promise of a string
async function fetchName(): Promise<string> {
return "Alice";
}
// TypeScript infers the awaited type
async function main() {
const age = await fetchAge(); // age: number
const name = await fetchName(); // name: string
}
When you declare a function with async, TypeScript automatically wraps the return type in Promise. So async () => string is really () => Promise<string>.
// Explicitly typed Promise return
function loadUser(): Promise<{ id: number; name: string }> {
return Promise.resolve({ id: 1, name: "Bob" });
}
// Generic wrapper for delayed values
function delay<T>(ms: number, value: T): Promise<T> {
return new Promise(resolve => setTimeout(() => resolve(value), ms));
}
const result = await delay(1000, 42); // result: number
Key Takeaway: Promise<T> uses generics to type-safely wrap asynchronous values, ensuring you know exactly what type emerges when the Promise resolves.