Typing fetch
fetch is typed in lib.dom as returning Promise<Response>. Response.json() is Promise<any>. Your job is to treat the body as unknown and validate it into a type.
Detailed Explanation
The DOM lib describes the fetch function, Request, Response, and Headers. Those types are accurate about the platform API. They are silent about your JSON.
const res = await fetch("/api/user");
const data = await res.json(); // any
any assigns to User. The compiler is satisfied. The server can send { "error": "nope" } and you will read data.email and crash. Annotating const data: User = await res.json() is the same hole: the annotation is a claim, not a parse.
The typed pattern is:
- Check
res.ok(and maybestatus). Failure is a different type, not aUser. - Parse JSON as
unknown(await res.json() as unknown, or a wrapper that returnsunknown). - Narrow with a type guard or a schema library.
- Return
Userfrom the helper, so callers never seeResponse.
fetch itself can be wrapped: function getJson(url: string): Promise<unknown>. Overloads for your routes (getJson("/api/user"): Promise<User>) are a lie unless the wrapper validates. A generic getJson<T>(url: string): Promise<T> is an invitation to write getJson<User>(url) and skip the guard. Do not add that generic unless T is produced by a parser (z.infer<typeof UserSchema>).
Request typing: RequestInit is in lib.dom. method is string in older libs and a union of method names in newer ones. headers is HeadersInit. You can constrain your wrapper: method: "GET" | "POST". Bodies: JSON.stringify takes any in the lib; pass a value you already typed, not any.
no-cors and opaque responses have types that still look like Response but hide the body. The type will not stop you from calling .json(). Handle the mode in the wrapper.
For the fetch API as a network tool, see the JavaScript fetch page. Here, the rule is unknown then a guard.
Code Examples
1. Wrapper that returns unknown, then a guard.
// 1. Wrapper that returns unknown, then a guard.
type User = { id: string; email: string };
function isUser(value: unknown): value is User {
if (typeof value !== "object" || value === null) return false;
const rec = value as Record<string, unknown>;
return typeof rec.id === "string" && typeof rec.email === "string";
}
async function getJson(url: string): Promise<unknown> {
const res = await fetch(url);
if (!res.ok) throw new Error(String(res.status));
return (await res.json()) as unknown;
}
async function loadUser(id: string): Promise<User> {
const raw = await getJson(`/api/users/${id}`);
if (!isUser(raw)) throw new Error("invalid user");
return raw;
}2. Discriminated result instead of throw.
// 2. Discriminated result instead of throw.
type Load<T> = { ok: true; data: T } | { ok: false; status: number };
async function tryUser(id: string): Promise<Load<User>> {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) return { ok: false, status: res.status };
const raw = (await res.json()) as unknown;
if (!isUser(raw)) return { ok: false, status: 422 };
return { ok: true, data: raw };
}3. Do not do this — generic without a parser.
// 3. Do not do this — generic without a parser.
// async function getJson<T>(url: string): Promise<T> {
// return (await (await fetch(url)).json()) as T;
// }Common Gotchas
`res.json()` is `any`
a `User` annotation on the const is not validation.
`getJson<T>` is an assertion factory
only use `T` from a runtime schema.
`res.ok` is not in the type of `json()`
failed responses still parse a body. Branch first.
Query strings and path params are `string`
branding `UserId` at the fetch boundary still needs a runtime format check if the id came from the URL.