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.
Code
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
cURL to fetch ConverterTranslate a curl command into equivalent JavaScript fetch() code, handling the request method, headers, JSON or raw body, and basic auth.Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.Set-Cookie ParserParse one or more Set-Cookie header values into the cookie name, value, and attributes like Path, Domain, Expires, Max-Age, Secure, HttpOnly, and SameSite.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.