Template literal types
Relay’s HTTP layer has routes like GET /hooks/:source/:id. A handler for it receives
params: Record<string, string>, so params.sorce compiles, returns undefined at runtime, and
the webhook is stored under the wrong source. The pattern already says which params exist. A
template literal type lets the compiler read that string.
This lesson builds the type that turns "/hooks/:source/:id" into { source: string; id: string },
plus two smaller string types Relay uses for handler names and route keys.
Template literal types
Section titled “Template literal types”A template literal type looks like a template string, in a type position. It builds a string type from other string types:
type Method = "GET" | "POST"type RouteKey = `${Method} ${string}`
const a: RouteKey = "GET /hooks" // okconst b: RouteKey = "POST /jobs/42" // ok// @ts-expect-error: FETCH is not a Methodconst c: RouteKey = "FETCH /hooks"${string} accepts any string in that slot. A union in a slot makes a union of results:
`${"GET" | "POST"} /x` is "GET /x" | "POST /x". With two unions it is every combination.
Built-in string helpers
Section titled “Built-in string helpers”Uppercase, Lowercase, Capitalize and Uncapitalize change the case of a string type. The
common use is a derived name:
type HandlerName<Tag extends string> = `on${Capitalize<Tag>}`
type A = HandlerName<"jobFailed"> // "onJobFailed"type B = HandlerName<"jobQueued" | "jobSucceeded"> // "onJobQueued" | "onJobSucceeded"The union case works because a template literal type applied to a union produces one result per
member. In lesson 3 a mapped type’s as clause used this to rename keys.
Reading a string with infer
Section titled “Reading a string with infer”Lesson 1 used infer to pull a type out of a function. It also works on
strings. Put infer Name in a slot of a template literal pattern, and the compiler captures the
part of the string that sits there:
type Source<P extends string> = P extends `/hooks/${infer Name}` ? Name : never
type A = Source<"/hooks/github"> // "github"type B = Source<"/jobs/1"> // neverEach infer captures the shortest match it can, up to the next literal in the pattern. With
${infer Head}/${infer Tail}, Head is everything before the first /.
Route params
Section titled “Route params”Now the whole type. Three steps: split the path into segments, keep the segments that start with
:, and build an object from the names.
type Segments<P extends string> = P extends `${infer Head}/${infer Tail}` ? Head | Segments<Tail> : P
type ParamName<S extends string> = S extends `:${infer Name}` ? Name : never
type Simplify<T> = { [K in keyof T]: T[K] } & {}
type PathParams<P extends string> = Simplify<{ [K in ParamName<Segments<P>>]: string }>
type Hook = PathParams<"/hooks/:source/:id"> // { source: string; id: string }type Health = PathParams<"/health"> // {}Segments<"/hooks/:source/:id"> is "" | "hooks" | ":source" | ":id". ParamName is a
conditional type applied to a union, so it runs once per member and the non-params become never,
which disappears from a union. The mapped type then makes one string property per name.
Simplify flattens the result into a plain object type, so it reads as { source: string; id: string }
in hovers and in equality checks.
Segments calls itself on Tail. That is recursion, the next lesson, and it
is safe here because the string gets shorter each step.
Types do not run
Section titled “Types do not run”PathParams is only a type. The runtime still has to split the real path and fill the object. The
compiler cannot check that the two agree, so the one function that connects them is where a cast
is tempting. An overload avoids it:
type Simplify<T> = { [K in keyof T]: T[K] } & {}type Segments<P extends string> = P extends `${infer Head}/${infer Tail}` ? Head | Segments<Tail> : Ptype ParamName<S extends string> = S extends `:${infer Name}` ? Name : nevertype PathParams<P extends string> = Simplify<{ [K in ParamName<Segments<P>>]: string }>
function matchRoute<P extends string>(pattern: P, path: string): PathParams<P> | nullfunction matchRoute(pattern: string, path: string): Record<string, string> | null { const want = pattern.split("/") const got = path.split("/") if (want.length !== got.length) return null const params: Record<string, string> = {} for (const [i, w] of want.entries()) { const g = got[i] if (g === undefined) return null if (w.startsWith(":")) params[w.slice(1)] = g else if (w !== g) return null } return params}
const params = matchRoute("/hooks/:source/:id", "/hooks/github/42")// params: { source: string; id: string } | nullCallers see the first signature. The body sees the second. A caller can only break the promise by
passing a path that does not match the pattern, and then the answer is null.
Exercise
Section titled “Exercise”The starter has PathParams, HandlerName and RouteKey typed too widely, and matchRoute
returns null for everything. Write the types so the tests’ Expect<Equal<...>> checks pass, then
fill in matchRoute. The rules at the top list the exact behavior.
- A template literal type builds string types from other string types, and unions in a slot multiply.
Capitalize,Uppercase,LowercaseandUncapitalizederive names such asonJobFailed.inferinside a template literal captures part of a string, so a conditional type can parse it.PathParams<P>splits a pattern into segments, keeps the:nameones and maps them tostring.Simplifymakes the result a flat object.- Types describe the string, they do not read it. The runtime parser and the type are two pieces of code, joined by an overload.
Further reading
Section titled “Further reading”- Template Literal Types: unions in templates and the intrinsic string types.
- TypeScript 4.1: template literal types, key remapping and recursive conditional types.