Fetch API — Generic Helper Pattern for Pinning Response Types
Fetch API — Generic Helper Pattern for Pinning Response Types
💡 Why Learn This? — fetch Is Always a Leak Point for any
Response · res.json() · Generic Helper
1. The type of Response is known, but body is any
2. The most common pattern — as Promise<User>
Simple, but it can lie — even if the server suddenly returns a different shape, it passes compilation. Fine for small projects.
3. Generic helper — reusable, casts in one place
4. Truly safe — combine with runtime validation
Since the actual shape is validated at runtime, it cannot lie. Recommended when communicating with external APIs.
💡 💡 5 Practical fetch + TS Patterns
1. One fetchJson
Consolidating fetch into a single entry point lets you manage caching, logging, and error policy in one place.
2. as Promise
For external APIs, use runtime validation like zod to verify the shape safely.
3. Preserve status with a custom error like HttpError
Enables different UI handling per status (401 → login, 403 → permission notice).
4. RequestInit is a standard type — TS knows it
5. Next.js fetch accepts cache options
Next.js extends the standard fetch RequestInit, and the types are extended along with it.