Skip to content
jshacks.dev
TypeScript

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.

1 min read
Summarize in AI

A route like /users/:id/posts/:postId has two parameters. A type can read their names straight from the string.

params.tsTypeScript
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' }));
Text
/users/7/posts/12

RouteParams 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.

Share

More snippets

TypeScript

Make every property required with Required

Required of T removes the question mark from every property, which types a config object after its defaults have been filled in. TypeScript 5 and earlier.

1 min read
TypeScript

Declare types for an untyped module

Write a small .d.ts file with declare module so an untyped package gets real function signatures, instead of an implicit any error. TypeScript 5.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.