typescript / expert
Snippet
Recursive Template Literal Type Parsing for Structured Route Parameters
This expert snippet uses template literal types and conditional type inference to recursively extract dynamic parameter names from a URL route path string at compile time. By matching strings prefixed with dynamic segments (`/:Param`), TypeScript infer captures parameter keys and constructs a unified string literal union.
snippet.ts
typescript
1
2
3
4
5
6
7
8
type ExtractRouteParams<T extends string> =T extends `${string}/:${infer Param}/${infer Rest}`? Param | ExtractRouteParams<`/${Rest}`>: T extends `${string}/:${infer Param}`? Param: never;type Params = ExtractRouteParams<"/users/:userId/posts/:postId">;
Breakdown
1
type ExtractRouteParams<T extends string> =
Defines a generic type taking a string route template parameter T.
2
T extends `${string}/:${infer Param}/${infer Rest}`
Uses template literal pattern matching to isolate the dynamic segment before the next slash.
3
? Param | ExtractRouteParams<`/${Rest}`>
Infers the parameter name and recursively parses the remaining path string.
4
: T extends `${string}/:${infer Param}`
Handles terminal parameter segments located at the end of the route path.
5
type Params = ExtractRouteParams<"/users/:userId/posts/:postId">;
Evaluates the type to yield the exact union 'userId' | 'postId'.