← All Exercises

Typed Route Matcher with Template Literals

advancedtypescript~15min

Background

Routers need compile-time knowledge of path parameters so handlers can access params safely. Template-literal types can derive the parameter shape from the pattern string, while the runtime matcher enforces it.

Problem

Implement PathParams<P> to extract parameter names from patterns such as /users/:id and /users/:id/posts/:postId, and matchRoute(pattern, path) to return a typed parameter object or null. Segments must match exactly, parameters must be non-empty, and values must be decoded with decodeURIComponent.

Input

A JSON object with route (a key naming a known pattern) and path (a URL pathname).

Output

A JSON object of decoded parameter values, or null when the path does not match the pattern.

Sample tests

Sample 1

Input: {"route":"post","path":"/users/42/posts/7"}
Expected: {"id":"42","postId":"7"}

Sample 2

Input: {"route":"user","path":"/users/a%20b"}
Expected: {"id":"a b"}

Sample 3

Input: {"route":"post","path":"/users/42"}
Expected: null

Your solution

Learning objective

Practice template-literal type inference and runtime matching that agrees with compile-time parameter types.