Course contentsShow
← TypeScript
Lesson 856 of 1,79619. Template Literal TypesFree lesson

Building URL Builder Functions

Create functions that accept only valid paths as template literal types and enforce correct parameter objects.

Building URL Builder Functions

What you'll learn: You'll create type-safe functions that only accept valid URL paths and enforce the correct parameter objects for each route.

The Goal

Imagine you have an application with multiple routes like /users/:id, /posts/:postId/comments/:commentId, and /dashboard. You want a helper function that constructs these URLs safely—but you also want TypeScript to prevent you from passing the wrong parameters to the wrong route.

For example, if you call buildUrl('/users/:id', { id: 5 }), that should work. But buildUrl('/users/:id', { postId: 5 }) should fail at compile time because postId doesn't match the :id parameter.

How It Works

You combine template literal types to define valid paths, infer to extract parameter names from those paths, and conditional types to construct the required parameter object.

Here's the pattern:

// Define valid routes
type Route = '/users/:id' | '/posts/:postId/comments/:commentId' | '/dashboard';

// Extract params from a path
type RouteParams<T extends string> = 
  T extends `${infer _Start}:${infer Param}/${infer Rest}`
    ? { [K in Param | keyof RouteParams<Rest>]: string | number }
    : T extends `${infer _Start}:${infer Param}`
    ? { [K in Param]: string | number }
    : Record<string, never>;

// The builder function
function buildUrl<T extends Route>(
  path: T,
  ...args: keyof RouteParams<T> extends never ? [] : [RouteParams<T>]
): string {
  const params = args[0] as Record<string, string | number>;
  return path.replace(/:(\w+)/g, (_, key) => String(params[key]));
}

// Usage
buildUrl('/users/:id', { id: 42 });
// "/users/42"

buildUrl('/posts/:postId/comments/:commentId', { postId: 1, commentId: 2 });
// "/posts/1/comments/2"

buildUrl('/dashboard');
// "/dashboard" — no params needed

// buildUrl('/users/:id', { postId: 5 }); ❌ Error!

Breaking It Down

  1. Route union: Restricts which paths are valid
  2. RouteParams<T>: Uses infer to extract parameter names and builds an object type requiring those keys
  3. Conditional parameter: The ...args uses a conditional type to require a parameter object only if the route has parameters
  4. Runtime logic: The function body uses a simple regex replace to substitute parameter values

Key Takeaway: By combining template literal types with generic constraints and conditional types, you can create URL builder functions that enforce compile-time safety between paths and their required parameters—catching routing bugs before runtime.