0Pricing
TypeScript Academy · Lesson

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

Write typed fetch helper functions to safely consume HTTP APIs.

The Problem with fetch

The fetch API returns Promise and .json() returns Promise. Without types, you lose all safety.
const res = await fetch('/api/user');
const data = await res.json(); // data: any — unsafe

Generic Fetch Wrapper

Create a typed fetch helper that assumes the response shape.
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

Call the wrapper with an explicit type argument.
interface User { id: number; name: string; }
const user = await fetchJson<User>('/api/users/1');
console.log(user.name); // typed as string

Adding Error Handling

Extend the wrapper to return a Result type.
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

Type fetch options for POST/PUT requests.
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

Validate the response shape before returning it as the typed value.

AbortController Typing

Type AbortController and AbortSignal for cancellable requests.
const ctrl = new AbortController();
const data = await fetchJson<User>('/api/users/1', { signal: ctrl.signal });
setTimeout(() => ctrl.abort(), 5000);

Base URL Interceptor

Create an HTTP client class with a base URL.
class ApiClient {
  constructor(private baseUrl: string) {}
  get<T>(path: string): Promise<T> {
    return fetchJson<T>(`${this.baseUrl}${path}`);
  }
}

Typed Headers

Type request and response headers.
const headers: Record<string, string> = {
  Authorization: `Bearer ${token}`,
  'Content-Type': 'application/json',
};

Pagination Types

Type paginated API responses.
interface Paginated<T> { data: T[]; page: number; total: number; }
const result = await fetchJson<Paginated<User>>('/api/users?page=1');

Quick Check

What does `res.json() as Promise` do in a typed fetch wrapper?

Recap

Typing Fetch Responses with Generic Wrappers: mastered the key concepts and patterns.

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

  1. Typing Fetch Responses with Generic Wrappers
  2. Runtime Validation with Zod
  3. OpenAPI Codegen: Auto-Generated Types
  4. Type-Safe tRPC Client Overview
← Back to TypeScript Academy