Template Literal Types Route Parser
Parse route patterns at the type level with template literal types and infer so path parameters are extracted and checked without runtime regex duplication.
Code
type ExtractParams<TRoute extends string> =
TRoute extends `${infer _Start}:${infer Param}/${infer Rest}`
? { [K in Param | keyof ExtractParams<Rest>]: string }
: TRoute extends `${infer _Start}:${infer Param}`
? { [K in Param]: string }
: // 无参数路由
Record<never, never>;
type UserRoute = ExtractParams<'/users/:userId/posts/:postId'>;
// { userId: string; postId: string }
function matchRoute<TRoute extends string>(
route: TRoute,
path: string,
): ExtractParams<TRoute> | null {
const pattern = new RegExp(
'^' + route.replace(/:([A-Za-z]+)/g, '(?<$1>[^/]+)') + '$',
);
const groups = pattern.exec(path)?.groups;
return groups ? (groups as ExtractParams<TRoute>) : null;
}
const params = matchRoute('/users/:userId/posts/:postId', '/users/42/posts/7');
console.log(params?.userId, params?.postId);
const miss = matchRoute('/health', '/healthz');
console.log(miss);What to watch for
ExtractParams walks the route string one parameter at a time. Its first branch matches a segment shaped like a prefix, a :name, and a slash followed by more route; infer Param captures the name and the type recurses on the rest, while the mapped type unions that name with everything recovered deeper into the string. That recursion is why a two-parameter route yields { userId: string; postId: string } rather than just the first one. A trailing parameter with no following slash falls to the second branch, and routes without any parameter resolve to Record<never, never>.
matchRoute mirrors the type at runtime, once: it rewrites each :name into a named capture group through route.replace(/:([A-Za-z]+)/g, '(?<$1>[^/]+)'), anchors the pattern, and reads pattern.exec(path)?.groups. The matched groups are returned as ExtractParams<TRoute> | null, so params?.userId and params?.postId are typed without duplicating the parsing logic.
The miss case holds too — matching /health against /healthz returns null because the anchored pattern requires the whole string to match, and the | null return makes callers handle it explicitly.
Interactive Tools for This Topic
FAQ
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement.
Report a problem with this exampleOpens a pre-filled issue on GitHub.