Dynamic Segment Extraction
What you'll learn: You'll discover how to use template literal types to automatically parse route patterns like '/users/[id]/posts/:slug' into typed parameter objects at compile time.
The Routing Parameter Problem
When working with routing systems, you've seen patterns like '/users/[id]' or '/posts/:slug'. These dynamic segments indicate that parts of the URL are variable. But how do you ensure your code knows which parameters exist for which route?
Manual type definitions are error-prone. What if the route changes but the type doesn't? Dynamic segment extraction solves this by deriving the parameter type directly from the route string itself.
Parsing Segments with Template Literals
Using template literal types with infer, you can extract segments that match specific patterns:
type ExtractBracketParam<Path> =
Path extends `${infer _Start}[${infer Param}]${infer Rest}`
? Param | ExtractBracketParam<Rest>
: never;
type ExtractColonParam<Path> =
Path extends `${infer _Start}:${infer Param}/${infer Rest}`
? Param | ExtractColonParam<`/${Rest}`>
: Path extends `${infer _Start}:${infer Param}`
? Param
: never;
type RouteParams<Path> = {
[K in ExtractBracketParam<Path> | ExtractColonParam<Path>]: string
};
type UserRoute = RouteParams<'/users/[id]/posts/:slug'>;
// { id: string; slug: string }
The conditionals recursively scan the route string, extracting anything between [...] or after :, then construct an object type.
Why This Matters
This pattern powers type-safe routing libraries. Change '/users/[id]' to '/users/[userId]', and TypeScript immediately knows the parameter is now userId—no manual type updates needed.
Key Takeaway: Template literal types with recursive infer let you parse dynamic route segments at compile time, creating parameter objects that stay perfectly synchronized with your route definitions.