Generic Wrapper Functions for fetch
What you'll learn: How to build a reusable, type-safe fetch wrapper that accepts a generic type parameter and returns Promise<T>, giving you compile-time guarantees about API response shapes.
The Core Problem
In the previous lesson, you learned to create response type interfaces. But writing fetch().then(res => res.json()) and casting the result every single time is repetitive and error-prone. You end up scattering type assertions throughout your codebase.
The solution? A generic wrapper function that centralizes the fetch logic and accepts a type parameter representing what you expect to get back.
How Generic Wrappers Work
A generic wrapper looks like this in structure:
async function fetchJson<T>(url: string): Promise<T> {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json() as T;
}
The <T> is a type parameter—a placeholder for whatever type you specify when calling the function. The return type Promise<T> means "this function returns a promise that resolves to type T."
Using the Wrapper
Now instead of manually casting everywhere, you specify the type when calling:
interface User {
id: number;
name: string;
}
const user = await fetchJson<User>('/api/user/1');
// user is typed as User, not any or unknown
console.log(user.name); // TypeScript knows .name exists
The generic <User> tells TypeScript "this fetch will return a User object." You get autocomplete and type safety immediately.
Why This Matters
Think of the generic wrapper as a contract template. Instead of writing "I expect a User" at every call site with as User, you write it once in the function signature. The wrapper handles the repetitive parts (error checking, JSON parsing), while T adapts to whatever type you need.
Key Takeaway: Generic fetch wrappers accept a type parameter <T> and return Promise<T>, centralizing fetch logic while preserving type safety for any response shape you specify at the call site.