Typed fetch client

A typed fetch client wraps fetch in a generic function that returns typed data. Because response.json() guarantees nothing at runtime, you must check the HTTP status and validate or narrow the shape of the data before trusting it, rather than asserting it with a simple assertion.

Example

async function getJson<T>(url: string): Promise<T> {
  const r = await fetch(url);
  if (!r.ok) throw new Error(`HTTP ${r.status}`);
  return (await r.json()) as T;
}

Related concepts

The whole glossary