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

Type-Safe Route Parameters

Extract parameter names from route template strings like '/user/:id/post/:postId' as typed unions.

Type-Safe Route Parameters

What you'll learn: How to automatically extract parameter names like 'id' and 'postId' from route template strings such as '/user/:id/post/:postId' and turn them into type-safe unions.

The Problem: Manual Route Parameter Typing

When building web applications with routes like '/user/:id/post/:postId', you typically have to manually define which parameters exist. This creates opportunities for typos and mismatches between your route definitions and the code that accesses those parameters.

Extracting Route Parameters with Template Literals

Template literal types let you pattern-match against string shapes and extract the dynamic parts. By combining conditional types with infer, you can pull parameter names right out of route strings:

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

This checks if a string segment matches the pattern :something and captures that something as the parameter name.

Building the Full Route Parser

For complete routes with multiple segments, you need to recursively parse each part:

type ExtractRouteParams<Path extends string> =
  Path extends `${infer Segment}/${infer Rest}`
    ? ExtractParam<Segment> | ExtractRouteParams<Rest>
    : ExtractParam<Path>;

This splits the route on slashes, extracts parameters from each segment, and unions them all together. For '/user/:id/post/:postId', TypeScript automatically produces 'id' | 'postId'.

From Parameter Union to Type-Safe Objects

With the parameter union in hand, you can create precisely-typed parameter objects:

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

Now RouteParams<'/user/:id/post/:postId'> becomes { id: string; postId: string } — completely derived from the route string itself!

Key Takeaway: Template literal types with recursive pattern matching let you extract parameter names from route strings at compile time, turning string templates into fully type-safe parameter objects without any manual duplication.