Template literal types
Template literal types describe a string pattern at the type level, like a template string in code, so the compiler checks a key format before running. Given a union they produce every combination, and infer can extract parts of the string, such as path parameters. Only literals known at compile time are checked: external data has type string and is validated at runtime.
TypeScript · Advanced types
A mock helper accepts the string "POST /transfers" while the real route is /api/v1/transfers. How do we teach the type to tell them apart?
A helper registers a mock for a request: mock('POST /api/v1/transfers', handler). The key is a string, and a typo in it breaks nothing visibly: the handler quietly never fires while the test waits for a response. The type string does not know what is allowed here. This lesson covers template literal types: string types built from a template that check the format before the code runs.
How it works and why. A template literal type is written like a template string, only at the type level: `/api/${Version}/${string}`. The substitution can hold literal types, unions, string, number or bigint. When a union is substituted, you get every combination (a Cartesian product): two methods times two versions make four string types. ${string} means "any string in this position", ${number} any string that parses as a number. The built-in utilities Uppercase, Lowercase, Capitalize, Uncapitalize change the case of a literal.
A template and its combinations
A separate feature: infer inside a template extracts parts of a string, like a regular expression but at the type level. More on that below.
Example: a key that accepts anything. A helper with a string key:
const handlers: Record<string, Handler> = {};
function mock(key: string, handler: Handler) {
handlers[key] = handler;
}
mock('POST /api/v1/transfer', createTransfer);
mock('POST /transfers', createTransfer);
Both calls compile. In the first there is a typo, transfer instead of transfers, and in the second the /api/v1 prefix is missing. Keys that no request matches got into the registry, so the handlers never run, and the test waits for a response that does not come.
The fix: describe the allowed key format with a type.
type Method = 'GET' | 'POST' | 'PUT' | 'DELETE';
type Version = 'v1' | 'v2';
type ApiPath = `/api/${Version}/${string}`;
type RouteKey = `${Method} ${ApiPath}`;
const ok: RouteKey = 'POST /api/v1/transfers';
const bad: RouteKey = 'POST /transfers'; // compile error
const handlers: Partial<Record<RouteKey, Handler>> = {
'GET /api/v1/accounts': listAccounts,
'POST /api/v1/transfers': createTransfer,
};
function mock(key: RouteKey, handler: Handler) {
handlers[key] = handler;
}
Now the key 'POST /transfers' does not compile, and the editor suggests the method and the prefix. The convention is written once in a type and works in every call.
A route key
key: string
Any string passes. A typo becomes a dead handler and a test that waits for nothing.
key: RouteKey
The compiler checks the format: the method and the /api/v1 prefix.
Extracting parts of a string. Sometimes a format is worth not only checking but parsing. The path parameters can be extracted straight from the route string:
type Params<P extends string> =
P extends `${string}:${infer Name}/${infer Rest}`
? Name | Params<`/${Rest}`>
: P extends `${string}:${infer Name}`
? Name
: never;
function route<P extends string>(
path: P,
handler: (params: Record<Params<P>, string>) => void,
) {}
route('/accounts/:id/transfers/:tid', (p) => {
console.log(p.id, p.tid);
});
The type Params looks in the template for a :Name section up to the next / and processes the rest recursively. For '/accounts/:id/transfers/:tid' the result is 'id' | 'tid', so handler receives an object with the keys id and tid, and access to a nonexistent parameter does not compile. For a path without parameters the result is never, that is an empty object.
Other useful applications. Conventions checked by the compiler:
type TestId = `${'btn' | 'input' | 'row'}-${string}`;
type TransferEvent = `transfer.${'created' | 'completed' | 'failed'}`;
type IsoDate = `${number}-${number}-${number}`;
type Env = 'dev' | 'stage';
type BaseUrl = `https://${Env}.bank.example`;
TestId enforces prefixes in a helper over getByTestId. TransferEvent describes event or metric keys. IsoDate gives a rough restriction that catches obvious mistakes but does not validate a date: the string '1-2-3' passes too.
Limits and alternatives.
- Template types work only with literals known at compile time. A string from
process.envor from an API response has typestringand still has to be checked at runtime (a type guard, a schema, a regular expression). - Combinations multiply: three unions of ten members each make a thousand string types. The compiler has a limit on union size and complains when it is exceeded, and large unions slow the build.
- Types do not validate values:
${number}accepts'1e3'and'-0'. For strict validation (a date, an email, an IBAN) a function is needed, and the type only helps. - Recursive templates are hard to read, so they are confined to the library layer and documented with a usage example.
Common mistakes.
- Thinking
IsoDatevalidates a date: it checks only the shape "number-number-number". - Expecting an error on a value from
process.env: it has typestring, not a literal. - Generating huge unions with a template: the build slows down and the compiler may refuse.
- Forgetting
as constfor a variable later passed to a function with a template type:const key = 'GET /api/v1/x'keeps the literal, whilelet key = …widens tostring.
Check yourself
The string const url = process.env.API_URL is passed to a function that accepts `https://${Env}.bank.example`. Why does the compiler reject it, and what should be done?
Answer
A value from process.env has type string | undefined, while a template type accepts only literals of a known shape. Data from outside is checked at runtime (a type guard or a schema), and only then is the type narrowed.
How many string types does `${'GET' | 'POST'} /v${1 | 2 | 3}` give, and why does it matter?
Answer
Six: 2 × 3. A template over unions gives every combination, so the result size multiplies, and with large unions the compiler slows down or reports a type that is too complex.
/api/. For unions they give all combinations. Middle/Senior: I use them for conventions (route keys, test ids, environment URLs), and with infer I extract, for example, path parameters. But it is compile time only: data from outside has type string and is validated separately, and large combinations slow the build.