Typing Fetch Responses with Generic Wrappers
Write a typed fetch helper that returns safe types.
Typing Fetch Responses with Generic Wrappers is a free TypeScript Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the TypeScript Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Welcome
The Problem with fetch
const res = await fetch('/api/user');
const data = await res.json(); // data: any — unsafeGeneric Fetch Wrapper
async function fetchJson<T>(url: string): Promise<T> {
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP error: ${res.status}`);
return res.json() as Promise<T>;
}Using the Wrapper
interface User { id: number; name: string; }
const user = await fetchJson<User>('/api/users/1');
console.log(user.name); // typed as stringAdding Error Handling
async function safeFetch<T>(url: string): Promise<Result<T>> {
try {
const res = await fetch(url);
if (!res.ok) return err(new Error(`HTTP ${res.status}`));
return ok(await res.json() as T);
} catch (e) { return err(e as Error); }
}Request Options Typing
async function postJson<T, B>(url: string, body: B): Promise<T> {
const res = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
return res.json() as Promise<T>;
}Response Validation
AbortController Typing
const ctrl = new AbortController();
const data = await fetchJson<User>('/api/users/1', { signal: ctrl.signal });
setTimeout(() => ctrl.abort(), 5000);Base URL Interceptor
class ApiClient {
constructor(private baseUrl: string) {}
get<T>(path: string): Promise<T> {
return fetchJson<T>(`${this.baseUrl}${path}`);
}
}Typed Headers
const headers: Record<string, string> = {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
};Pagination Types
interface Paginated<T> { data: T[]; page: number; total: number; }
const result = await fetchJson<Paginated<User>>('/api/users?page=1');Quick Check
Recap
Frequently asked questions
Is the “Typing Fetch Responses with Generic Wrappers” lesson free?
Yes — the full text of “Typing Fetch Responses with Generic Wrappers” is free to read here on the web, and the TypeScript Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the TypeScript Academy course, upgrade to CoddyKit PRO.
What will I learn in “Typing Fetch Responses with Generic Wrappers”?
Write a typed fetch helper that returns safe types. You practise TypeScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start TypeScript Academy?
No prior experience is required. TypeScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Typing Fetch Responses with Generic Wrappers” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this TypeScript Academy lesson?
Yes. Every TypeScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Typing Fetch Responses with Generic Wrappers
- Runtime Validation with Zod
- OpenAPI Codegen: Auto-Generated Types
- Type-Safe tRPC Client Overview