How would you build a fully type-safe route-parameter object type (like Express or React Router param typing) using recursive template literal parsing?
Short answer
Recursively walk the route string literal type using conditional types with 'infer', peeling off one `:param` segment at a time, and use a mapped type (via Record) to assemble the final object type mapping every discovered parameter name to 'string' — this is exactly the…
Advertisement
AModel answer
Recursively walk the route string literal type using conditional types with 'infer', peeling off one `:param` segment at a time, and use a mapped type (via Record) to assemble the final object type mapping every discovered parameter name to 'string' — this is exactly the technique modern type-safe routing libraries use internally.
type ParseParams<T extends string> =
T extends `${string}:${infer Param}/${infer Rest}`
? { [K in Param | keyof ParseParams<Rest>]: string }
: T extends `${string}:${infer Param}`
? { [K in Param]: string }
: {};
type Params = ParseParams<'/users/:userId/posts/:postId'>;
// { userId: string; postId: string }Real-world example
Building a fully type-safe routing library where navigating to a route automatically requires and types its exact set of URL parameters.
Likely follow-ups
- What real-world libraries (like React Router's typed routes, or tRPC) rely on exactly this kind of type-level string parsing technique?
Related topics