Typed Fetch Client With Endpoints

Build a small HTTP client whose methods are typed against endpoint definitions, so request bodies and response shapes are checked at the call site.

TypescriptData Fetching

Code

typescriptsnippet
20 lines
export interface Endpoints {
  "GET /users/:id": { params: { id: string }; response: { id: string; name: string } };
  "POST /users": { body: { name: string }; response: { id: string } };
}

export function createClient(baseUrl: string) {
  async function call<
    K extends keyof Endpoints,
    E extends Endpoints[K],
  >(key: K, arg: E extends { body: infer B } ? B : E extends { params: infer P } ? P : never): Promise<E extends { response: infer R } ? R : never> {
    const [method, path] = (key as string).split(" ");
    const url = baseUrl + path.replace(/:id/, (arg as { id?: string }).id ?? "");
    const response = await fetch(url, {
      method,
      body: method === "GET" ? undefined : JSON.stringify(arg),
    });
    return (await response.json()) as never;
  }
  return { call };
}

How this snippet works

The working surface is the functions createClient and call — everything else is wiring.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

A fresh value is allocated for the result; the arguments stay untouched.

What to watch for

  • Uses fetch, so it needs a browser context — it will not run as-is in Node without shims.

Using it

The primary signature is export function createClient(baseUrl: string)

createClient is the public entry point; everything else in the file exists to support it.

Key statements

return (await response.json()) as never;
const url = baseUrl + path.replace(/:id/, (arg as { id?: string }).id ?? "");
const response = await fetch(url, {
method,
body: method === "GET" ? undefined : JSON.stringify(arg),
});

Interactive Tools for This Topic

FAQ

Does `createClient` modify its input?
It does not. Inputs are only read; the return value is freshly built.
Anything to download besides the language toolchain?
Nothing beyond the toolchain you already have for this language. The file defines `createClient`, `call` at load time.