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'

Explanation

Routers like TanStack Router and typed Express helpers use this to make params.id type-safe.

Further reading

Problem with a question

TypeScript · Senior · question 53

Test yourself

Take the TypeScript · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz