capypad
0 day streak
typescript / expert
Snippet

Recursive Template Literal Type Parsing

This snippet uses template literal types and recursive conditional types to extract dynamic path parameters from a string literal at compile time. It demonstrates how TypeScript can parse strings to build complex object types based on naming conventions like ':param'.

snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
type ExtractParams<T extends string> =
T extends `${string}:${infer Param}/${infer Rest}`
? { [K in Param | keyof ExtractParams<Rest>]: string }
: T extends `${string}:${infer Param}`
? { [K in Param]: string }
: {};
 
const route = "/user/:id/posts/:postId";
type RouteParams = ExtractParams<typeof route>;
// Result: { id: string; postId: string; }
Breakdown
1
T extends `${string}:${infer Param}/${infer Rest}`
Checks if the string contains a colon followed by a segment before a slash, capturing both the parameter and the remainder.
2
{ [K in Param | keyof ExtractParams<Rest>]: string }
Recursively maps the captured parameter and joins it with parameters extracted from the rest of the string.