Lesson 4 of 7
Typed fetch & Abort Controller
`fetch()` returns `Promise<Response>` and `.json()` returns `Promise<any>` - which is unsafe. Wrapping fetch in a typed, validated utility eliminates unsafe `any` from your codebase. `AbortController` lets you cancel in-flight requests with full TypeScript support.
Typed fetch Wrapper & AbortController
import type { ZodSchema } from "zod";
// ── Problem: fetch().json() returns Promise<any> ──────────────
const raw = await fetch("/api/tasks").then(r => r.json());
// raw is any → no type safety, runtime surprises guaranteed
// ── Typed fetch wrapper - validates AND types the response ─────
type FetchConfig = {
method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
body?: unknown;
headers?: Record<string, string>;
signal?: AbortSignal;
};
async function apiFetch<T>(
path: string,
schema: ZodSchema<T>,
config: FetchConfig = {},
): Promise<T> {
const { method = "GET", body, headers = {}, signal } = config;
const res = await fetch(`/api${path}`, {
method,
signal,
headers: {
"Content-Type": "application/json",
...headers,
},
body: body !== undefined ? JSON.stringify(body) : undefined,
});
if (!res.ok) {
const errorBody: unknown = await res.json().catch(() => null);
const message =
errorBody &&
typeof errorBody === "object" &&
"message" in errorBody
? String((errorBody as { message: unknown }).message)
: `HTTP ${res.status} ${res.statusText}`;
throw new Error(message);
}
const data: unknown = await res.json();
return schema.parse(data); // Zod validates AND infers the type
}
// ── Zod schema usage ──────────────────────────────────────────
import { z } from "zod";
const TaskSchema = z.object({
id: z.number(),
title: z.string(),
status: z.enum(["todo", "in-progress", "done", "archived"]),
priority: z.enum(["low", "medium", "high", "critical"]),
});
type Task = z.infer<typeof TaskSchema>; // derived from Zod schema!
// Usage:
const task = await apiFetch("/tasks/1", TaskSchema);
// task is Task - validated and typed ✅
// ── AbortController - cancel requests ────────────────────────
class TaskApiClient {
private abortControllers = new Map<string, AbortController>();
async fetchTask(id: number): Promise<Task> {
// Cancel previous request for same ID if still in-flight
this.abortControllers.get(`task-${id}`)?.abort();
const controller = new AbortController();
this.abortControllers.set(`task-${id}`, controller);
try {
return await apiFetch(`/tasks/${id}`, TaskSchema, { signal: controller.signal });
} finally {
this.abortControllers.delete(`task-${id}`);
}
}
cancelAll(): void {
this.abortControllers.forEach((ctrl) => ctrl.abort());
this.abortControllers.clear();
}
}
// ── Detecting abort in catch ──────────────────────────────────
try {
const task = await apiFetch("/tasks/1", TaskSchema, { signal: controller.signal });
} catch (error: unknown) {
if (error instanceof DOMException && error.name === "AbortError") {
console.log("Request was cancelled"); // handle abort separately
} else {
throw error; // re-throw non-abort errors
}
}Common Mistakes
- Trusting `fetch()` without validation - even with a TypeScript type cast (`as Task`), the server can return anything. Parse with Zod and the type is both checked AND typed.
- Not checking `res.ok` - `fetch` only rejects on network failure, not HTTP errors (404, 500). Always check `res.ok` before parsing the response body.
- Not handling AbortError separately - aborting a fetch throws a `DOMException` with `name === 'AbortError'`. If you don't distinguish it from real errors, aborted requests look like failures in your error tracking.
Tip
Tip
Practice Typed fetch Abort Controller in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Typed fetch & Abort Controller
Practice Task
Note
Practice Task - (1) Write a working example of Typed fetch Abort Controller from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Typed fetch Abort Controller is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready typescript code.
Key Takeaways
- `fetch()` returns `Promise<Response>` and `.
- Trusting `fetch()` without validation - even with a TypeScript type cast (`as Task`), the server can return anything. Parse with Zod and the type is both checked AND typed.
- Not checking `res.ok` - `fetch` only rejects on network failure, not HTTP errors (404, 500). Always check `res.ok` before parsing the response body.
- Not handling AbortError separately - aborting a fetch throws a `DOMException` with `name === 'AbortError'`. If you don't distinguish it from real errors, aborted requests look like failures in your error tracking.
Finished this lesson?