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.
Ctrl+Enter runs the tests. Tab indents; to leave the editor with the keyboard, press Esc and then Tab. Your code is saved in this browser.
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.
- types
type _ = Expect<Equal<RouteParams<'/users/:id/posts/:postId'>, { id: string; postId: string }>>;
- types
type _ = Expect<Equal<RouteParams<'/about'>, {}>>;
- types
buildPath('/users/:id', { id: '42' });
- types
// @ts-expect-error - postId is missing buildPath('/users/:id/posts/:postId', { id: '1' });
expect(buildPath('/users/:id/posts/:postId', { id: '7', postId: '9' })).toBe('/users/7/posts/9');
expect(buildPath('/search/:query', { query: 'a b/c' })).toBe('/search/a%20b%2Fc');
expect(buildPath('/about', {})).toBe('/about');