← All tasksTypeScript · Senior

Route params from a string

Routers like React Router and Express describe a route as a string: /users/:id/posts/:postId. Write a type RouteParams<Path> that turns such a string into a params object { id: string; postId: string } and gives {} for a route without params.

With it, buildPath(pattern, params) will require exactly the params the route has and substitute them into the path, encoding values with encodeURIComponent.

Tests (7)

Type tests are checked by the TypeScript compiler in strict mode. Expect<Equal<A, B>> passes when the types match exactly, and // @ts-expect-error passes when the next line does not compile. The first run downloads the compiler, so it takes a few seconds.

  1. types
    type _ = Expect<Equal<RouteParams<'/users/:id/posts/:postId'>, { id: string; postId: string }>>;
  2. types
    type _ = Expect<Equal<RouteParams<'/about'>, {}>>;
  3. types
    buildPath('/users/:id', { id: '42' });
  4. types
    // @ts-expect-error - postId is missing
    buildPath('/users/:id/posts/:postId', { id: '1' });
  5. expect(buildPath('/users/:id/posts/:postId', { id: '7', postId: '9' })).toBe('/users/7/posts/9');
  6. expect(buildPath('/search/:query', { query: 'a b/c' })).toBe('/search/a%20b%2Fc');
  7. expect(buildPath('/about', {})).toBe('/about');