API Client Path Generation
What you'll learn: How to use template literal types to automatically generate typed API client methods that match your route definitions, catching parameter mismatches at compile time.
The Problem We're Solving
When building API clients, you typically have a set of endpoints like /users/:id or /posts/:postId/comments/:commentId. Manually writing methods for each endpoint is tedious and error-prone — you might misspell a parameter, pass the wrong type, or forget a required parameter entirely.
Template literal types let us generate the entire client interface from path definitions, ensuring every method call matches the expected route structure.
Basic API Client Generation
Building on our route parameter extraction knowledge, we can now create complete client methods:
type ExtractParams<Path extends string> =
Path extends `${infer _Start}:${infer Param}/${infer Rest}`
? Param | ExtractParams<`/${Rest}`>
: Path extends `${infer _Start}:${infer Param}`
? Param
: never;
type APIClient<Routes extends string> = {
[Route in Routes as `get${Capitalize<Route>}`]:
ExtractParams<Route> extends never
? () => Promise<Response>
: (params: Record<ExtractParams<Route>, string>) => Promise<Response>
};
type Routes = '/users/:userId' | '/posts/:postId/comments/:commentId';
type Client = APIClient<Routes>;
// {
// 'getUsers/:userId': (params: { userId: string }) => Promise<Response>
// 'getPosts/:postId/comments/:commentId': (params: { postId: string, commentId: string }) => Promise<Response>
// }
This generates a method for each route where parameters are required only when the path contains dynamic segments.
Why This Matters
The generated client enforces correctness at the type level. If you try calling client['getUsers/:userId']() without params, TypeScript catches it. If you pass { id: "123" } instead of { userId: "123" }, TypeScript catches that too. Your API contract is now encoded directly in the type system, making it impossible to construct invalid requests without the compiler warning you.
Key Takeaway: Template literal types transform route definitions into fully-typed API client methods, automatically extracting parameters and enforcing correct usage — turning runtime API errors into compile-time safety.