TypeScript

Typed Fetch Wrapper

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
A thin fetch wrapper that returns parsed JSON typed as `T`, throws on non-2xx, and accepts an AbortSignal. Single source of truth for "how this app talks to APIs."
TypeScript
Raw
export class HttpError extends Error {
  constructor(public status: number, public body: unknown, message?: string) {
    super(message ?? `HTTP ${status}`);
  }
}

export async function http<T>(url: string, opts: RequestInit = {}): Promise<T> {
  const r = await fetch(url, {
    ...opts,
    headers: { 'Accept': 'application/json', ...(opts.headers ?? {}) },
  });
  const isJson = r.headers.get('content-type')?.includes('application/json');
  const body   = isJson ? await r.json().catch(() => null) : await r.text();
  if (!r.ok) throw new HttpError(r.status, body, `HTTP ${r.status} on ${url}`);
  return body as T;
}

const user = await http<{ id: number; name: string }>('/api/users/42');
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.