Lesson 6 of 9 · 21m
Template Literal Types: Make Strings Carry Meaning
Using literal string patterns for routes, CSS units, event names, and command vocabularies — with honest limits around runtime validation.
Most applications are full of strings that are not really arbitrary strings. Routes look like /users/:id, event names look like invoice.paid, CSS dimensions look like 16px or 2rem, and command names come from a fixed product vocabulary. Template literal types let you encode that structure so autocomplete and the compiler do part of the review for you.
Fixed vocabularies beat documentation
type Environment = "dev" | "staging" | "prod";
type Region = "us-east" | "eu-west";
type Hostname = `${Environment}.${Region}.internal.sudosecurity.org`;
const primary: Hostname = "prod.us-east.internal.sudosecurity.org";
// const typo: Hostname = "production.us-east.internal.sudosecurity.org"; // errorThis is not just ceremony. Infrastructure code is full of generated names — buckets, queues, hosts, topics — and typos there are expensive.
Extracting structure with infer
type RouteParams<Path> =
Path extends `${string}:${infer Param}/${infer Rest}`
? Param | RouteParams<`/${Rest}`>
: Path extends `${string}:${infer Param}`
? Param
: never;
type Params = RouteParams<"/users/:userId/invoices/:invoiceId">;
// "userId" | "invoiceId"You do not need to implement a router to benefit. Even simple extraction can align path helpers with parameter objects:
function buildPath<Path extends string>(
path: Path,
params: Record<RouteParams<Path>, string>,
) {
return Object.entries(params).reduce(
(acc, [key, value]) => acc.replace(`:${key}`, value),
path,
);
}The compiler now rejects missing or misspelled params before integration tests do.
Template literals are compile-time patterns, not validators
A template literal type can say a string looks like user_${string}. It cannot prove the runtime string came from your trusted helper unless the value is typed through that path. Boundaries still need parsing.
Field notes
- Huge unions generated from template literals can slow the compiler; constrain the pieces before multiplying them.
string & keyof Tis often necessary because keys may bestring | number | symbol.- Prefer template literal types for stable product vocabularies, not every string in the codebase.
- When users can input these strings, parse into a branded type rather than trusting the raw value.
Was this lesson helpful?