Type a fetch response safely

Typescript

unknown forces a parse step rather than letting an any spread silently through the codebase.

async function getJson<T>(url: string, parse: (u: unknown) => T): Promise<T> {
  const res = await fetch(url);
  if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
  return parse(await res.json());
}

More in TypeScript

Random picks