API Response Wrappers
What You'll Learn
You'll learn how to use generic types like Result<T>, Option<T>, or ApiResponse<T> to wrap API responses while preserving the exact type of the payload data inside.
Why API Response Wrappers Matter
When calling external APIs or handling asynchronous operations, you don't just get back raw data—you get metadata too: success/failure status, error messages, HTTP codes, loading states, etc. Without generics, you'd either lose type safety on the payload or write separate wrapper types for every single data shape.
Generic wrappers solve this perfectly. They let you define the "envelope" structure once, then slot in any payload type T you need.
Common Wrapper Patterns
Result Type
Represents success or failure with a payload:
type Result<T> =
| { success: true; data: T }
| { success: false; error: string };
function fetchUser(id: number): Result<{ name: string; age: number }> {
// Implementation would go here
return { success: true, data: { name: "Alice", age: 30 } };
}
const userResult = fetchUser(1);
if (userResult.success) {
console.log(userResult.data.name); // TypeScript knows 'data' exists and has 'name'
}
ApiResponse Type
Includes HTTP metadata:
type ApiResponse<T> = {
status: number;
data: T;
timestamp: string;
};
function getProduct(): ApiResponse<{ id: number; title: string }> {
return {
status: 200,
data: { id: 42, title: "Widget" },
timestamp: "2024-01-01"
};
}
The Power of Preservation
The magic is that T preserves whatever type you specify. Result<User> knows the data is a User. ApiResponse<Product[]> knows it's an array of products. You write the wrapper once, use it everywhere, and never lose type information.
Key Takeaway: Generic API response wrappers let you standardize how you handle success/failure/metadata across all endpoints while keeping complete type safety on each unique payload type.