TypeScript · Senior · Question 53 of 75
How do you extract route params from a path string type?
type Params<P> = P extends `${string}:${infer K}/${infer R}`
? K | Params<R>
: P extends `${string}:${infer K}` ? K : never;
type T = Params<'/users/:id/posts/:postId'>; // 'id' | 'postId'- ✓Correct answer: With recursive template literal types and
infer - 2Only at runtime with regex
- 3With
keyofon the string
Explanation
Routers like TanStack Router and typed Express helpers use this to make params.id type-safe.