Async Operations and Promises
What you'll learn: Why Promise<T> uses generics to guarantee that asynchronous operations return the correct types when they finally complete.
The Async Type Safety Problem
When you perform asynchronous operations (fetching data, reading files, waiting for timers), the result doesn't arrive immediately—it comes later. Without generics, TypeScript couldn't know what type that future value would be. Should a database query promise resolve to a User, an Order, or just any? The type parameter T in Promise<T> solves this.
How Promise<T> Guarantees Type Safety
The Promise type is generic because different async operations resolve to different value types:
const userPromise: Promise<{ id: number; name: string }> = fetchUser(1);
const countPromise: Promise<number> = getItemCount();
const voidPromise: Promise<void> = saveSettings();
When you await or .then() a promise, TypeScript knows exactly what type you'll receive:
async function displayUser() {
const user = await userPromise; // user is { id: number; name: string }
console.log(user.name); // ✓ Type-safe access
// console.log(user.age); // ✗ Error: property doesn't exist
}
Type Safety Across Async Boundaries
Generics ensure that the type you put into an async operation is the type you get out when it completes. If you create new Promise<string>((resolve) => ...), TypeScript enforces that resolve() must be called with a string. If you chain .then(), each step's input type matches the previous step's return type—all tracked through the generic parameter.
Key Takeaway: Promise<T> is generic so TypeScript can track what type an asynchronous operation will eventually produce, maintaining type safety even when values arrive in the future rather than immediately.