Chapter 7: Template Literal Types
Runnable examples: examples/ch07-template-literal-types.ts
Template literal types (TypeScript 4.1+) bring string templates to the type level. They build string types, and with infer, they parse them.
Building: unions multiply
type Size = "sm" | "md" | "lg";
type Side = "top" | "bottom";
type MarginClass = `m${Capitalize<Side>}-${Size}`;
// "mTop-sm" | "mTop-md" | "mTop-lg" | "mBottom-sm" | "mBottom-md" | "mBottom-lg"
Every combination is produced: 2 sides x 3 sizes = 6 members. This is a cross product, so large unions can explode in size; TypeScript limits how big a union can get.
Intrinsic string helpers
Uppercase<S>, Lowercase<S>, Capitalize<S> and Uncapitalize<S> are built into the compiler.
Parsing with infer
type Split<S extends string, D extends string> =
S extends `${infer Head}${D}${infer Tail}` ? [Head, ...Split<Tail, D>] : [S];
type Parts = Split<"a.b.c", ".">; // ["a", "b", "c"]
How matching works: an infer placeholder followed by a literal matches as little as possible (up to the first occurrence of the delimiter). The last placeholder takes the rest.
A real use: typed route parameters
type RouteParams<Path extends string> =
Path extends `${string}:${infer Param}/${infer Rest}`
? { [K in Param | keyof RouteParams<`/${Rest}`>]: string }
: Path extends `${string}:${infer Param}`
? { [K in Param]: string }
: {};
type P = RouteParams<"/users/:userId/posts/:postId">; // { userId: string; postId: string }
The buildPath function in the examples uses it so that forgetting a parameter is a compile error:
buildPath("/users/:userId/posts/:postId", { userId: "42", postId: "7" }); // OK
buildPath("/users/:userId/posts/:postId", { userId: "42" }); // Error: postId missing
Web frameworks and routers use the same technique to type URL parameters.
Deriving names from keys
type ChangeEvents<T> = { [K in keyof T & string as `${K}Changed`]: (value: T[K]) => void };
// ChangeEvents<{ name: string; age: number }> =
// { nameChanged: (value: string) => void; ageChanged: (value: number) => void }
Pattern types are not validators
type HexColor = `#${string}`;
const ok: HexColor = "#ff8800";
const alsoOk: HexColor = "#nothex"; // accepted: the pattern only requires a leading #
${string} matches any string, including the empty string. Template literal types check a pattern, not a full grammar. They are great for catching obvious mistakes in literals written in code; for data from users, files or APIs, validate at runtime.
Performance notes
- Deeply recursive string parsing is limited by the compiler’s recursion depth.
- Cross products of large unions get big quickly; avoid generating thousands of members.
- If editor hovers and type checking slow down, look for recursive template literal types first.
Check yourself
- How many members does
`${"a" | "b"}-${"x" | "y" | "z"}`have? - Why can
"#nothex"be assigned to`#${string}`? - In
S extends `${infer A}.${infer B}`, what isAfor"x.y.z"?
Answers
1. Six. 2. `${string}` matches any string; the type only requires the prefix. 3. `"x"` (the shortest match before the first dot), and `B` is `"y.z"`.Next: Chapter 8, Variance