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

Inferring Route Params from Path Strings

Use conditional types with template literals to extract parameter names into an object type for route handlers.

Inferring Route Params from Path Strings

What you'll learn: How to use conditional types with template literals to automatically extract parameter names from route path strings and create type-safe objects for route handlers.


When building web applications, routes often contain dynamic segments like /users/:userId/posts/:postId. Wouldn't it be amazing if TypeScript could automatically know which parameters your route expects?

The Core Problem

Imagine you're building a router where routes look like "/users/:id" or "/posts/:postId/comments/:commentId". You want TypeScript to infer that the first route expects { id: string } and the second expects { postId: string, commentId: string }.

The Solution: Conditional Types + Template Literals

You can build a type that extracts parameter names from route strings using infer with template literal patterns:

type ExtractParam<Path> = 
  Path extends `:${infer Param}` 
    ? Param 
    : never;

// Test it
type Test1 = ExtractParam<':userId'>; // 'userId'
type Test2 = ExtractParam<'static'>;  // never

For full paths with multiple segments, you need recursion:

type ExtractRouteParams<Path> = 
  Path extends `${infer _Start}:${infer Param}/${infer Rest}`
    ? Param | ExtractRouteParams<`/${Rest}`>
    : Path extends `${infer _Start}:${infer Param}`
    ? Param
    : never;

type Params = ExtractRouteParams<'/users/:userId/posts/:postId'>;
// 'userId' | 'postId'

Now convert that union into an object type:

type RouteParams<Path> = {
  [K in ExtractRouteParams<Path>]: string
};

type UserPostParams = RouteParams<'/users/:userId/posts/:postId'>;
// { userId: string; postId: string }

Your route handler can now be type-safe:

function handleRoute<Path extends string>(
  path: Path,
  handler: (params: RouteParams<Path>) => void
) {
  // Implementation would parse actual params
}

handleRoute('/users/:userId', (params) => {
  params.userId; // ✓ TypeScript knows this exists!
});

Key Takeaway: By combining conditional types, infer in template literal patterns, and mapped types, you can extract dynamic route segments from path strings and generate properly-typed parameter objects—giving you autocomplete and type safety for your routing layer.