Use infer in template literals to parse strings
Parse a string literal type with infer inside a template literal type to read the parameters of a route pattern. Needs TypeScript 4.1 or later.
A route like /users/:id/posts/:postId has two parameters. A type can read their names straight from the string.
type Params<S extends string> =
S extends `${string}:${infer Name}/${infer Rest}`
? Name | Params<`/${Rest}`>
: S extends `${string}:${infer Name}`
? Name
: never;
type RouteParams = Params<'/users/:id/posts/:postId'>;
function buildPath(template: string, params: Record<RouteParams, string>): string {
return template.replace(/:(\w+)/g, (_match, name: string) => params[name as RouteParams]);
}
console.log(buildPath('/users/:id/posts/:postId', { id: '7', postId: '12' }));/users/7/posts/12RouteParams is 'id' | 'postId'. The first branch takes the text between : and the next /, then recurses on the rest, and the second branch handles a final parameter. A call that omits postId is a compile error. The pattern matching is explained in the template literal types chapter.
Here buildPath accepts any string template, so the compiler cannot connect it to the parameters; make the template a generic S and use Params<S> to tie them together. Types like this slow the compiler on long patterns, so keep them for a handful of routes.