typescript / expert
Snippet
Compile-Time Route Parameter Extraction for Framework Routers
This snippet demonstrates how framework authors can extract route parameters dynamically from a path string literal at compile time using TypeScript template literal inference and recursion. The result is auto-completed route handler parameters without manual type annotations.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
type ExtractRouteParams<Path extends string> =Path extends `${string}:${infer Param}/${infer Rest}`? { [K in Param | keyof ExtractRouteParams<`/${Rest}`>]: string }: Path extends `${string}:${infer Param}`? { [K in Param]: string }: {};class MicroRouter<const TPath extends string> {constructor(private readonly path: TPath) {}handle(callback: (params: ExtractRouteParams<TPath>) => void): void {// Implementation logic here}}const userRouter = new MicroRouter('/users/:userId/posts/:postId');userRouter.handle((params) => {console.log(params.userId, params.postId);});
Breakdown
1
type ExtractRouteParams<Path extends string> =
Defines a generic utility type that accepts a path string literal.
2
Path extends `${string}:${infer Param}/${infer Rest}`
Uses template literal pattern matching to infer the parameter name before a slash and the remainder of the path.
3
? { [K in Param | keyof ExtractRouteParams<`/${Rest}`>]: string }
Recursively constructs an object type mapping inferred parameter names to string values.
4
class MicroRouter<const TPath extends string> {
Uses a const type parameter modifier to preserve literal path string types upon instantiation.