Template Literal Types
A template literal type builds a string literal type from other string types, using the same ${...} syntax as a JavaScript template string. The result is a type, not a runtime string.
Detailed Explanation
JavaScript template literals stitch values into a string at runtime. Template literal types do the same job one layer up: they stitch types into a string type at compile time. The syntax looks familiar on purpose.
type EventName = `on${string}`;
That type is the set of every string that starts with on. "onClick" is in the set. "click" is not.
The useful case is combining known literals rather than the open string. If you have a union of event names and a union of prefixes, the template expands into the cartesian product:
type Event = "click" | "focus";
type Handler = `on${Capitalize<Event>}`; // "onClick" | "onFocus"
Capitalize, Uncapitalize, Uppercase, and Lowercase are intrinsic string manipulation types. They exist only in the type system. They do not call toUpperCase at runtime.
This is how many libraries type CSS properties, HTTP headers, event maps, and route strings. Instead of listing every combination by hand, you describe the grammar and let the compiler generate the union. The generated union is still a finite set of literals when the inputs are finite, so it participates in autocomplete and exhaustiveness checking.
Template literal types also work in the other direction through infer. You can parse a string type the way a regular expression would parse a string value:
type RouteParams<S extends string> =
S extends `${string}:${infer Param}/${infer Rest}`
? Param | RouteParams<`/${Rest}`>
: S extends `${string}:${infer Param}`
? Param
: never;
RouteParams<"/users/:id/posts/:postId"> becomes "id" | "postId". The pattern is a type-level parser. It is erased completely; the running program still has to parse the real URL with ordinary JavaScript.
Two limits matter in practice. First, a template that includes unbounded string or number produces a huge or infinite set, and the compiler will not enumerate it. You still get assignability checks ("onX" matches `on${string}`) but you lose autocomplete of every member. Second, very large expansions — a union of twenty literals crossed with another union of twenty — can slow the type checker or hit recursion limits.
Reach for template literal types when the string has structure you can describe: a prefix, a separator, a known vocabulary. Do not use them to re-implement a parser for free-form user input. That input is string until you validate it at runtime.
Code Examples
1. Building a closed set of handler names from event names.
// 1. Building a closed set of handler names from event names.
type DomEvent = "click" | "focus" | "blur";
type HandlerName = `on${Capitalize<DomEvent>}`;
// "onClick" | "onFocus" | "onBlur"
const handlers: Record<HandlerName, () => void> = {
onClick: () => {},
onFocus: () => {},
onBlur: () => {},
// onHover: () => {},
// Error: 'onHover' does not exist in type Record<HandlerName, () => void>.
};2. Constraining a CSS-like unit string.
// 2. Constraining a CSS-like unit string.
type Length = `${number}px` | `${number}em` | `${number}%`;
function setWidth(value: Length): void {
document.body.style.width = value;
}
setWidth("24px");
setWidth("2em");
// setWidth("24");
// Error: Argument of type '"24"' is not assignable to parameter of type 'Length'.3. Extracting a union of keys from a dotted path grammar.
// 3. Extracting a union of keys from a dotted path grammar.
type PropPath<T, Prefix extends string = ""> = {
[K in keyof T & string]:
T[K] extends object
? PropPath<T[K], `${Prefix}${K}.`> | `${Prefix}${K}`
: `${Prefix}${K}`;
}[keyof T & string];
type User = { id: number; profile: { email: string } };
type Paths = PropPath<User>; // "id" | "profile" | "profile.email"Common Gotchas
`${number}` is not a runtime number check
`"24px"` matches `${number}px` only as a type. A value that arrives as `string` from an input still needs a runtime parse before you treat it as a length.
Huge cartesian products stall the checker
crossing two large unions inside a template can explode into tens of thousands of members. Keep the input unions small, or introduce an intermediate named type.
Intrinsic helpers only accept string types
`Capitalize<0>` is an error. If a key might be a number or symbol, intersect with `string` first: `Capitalize<K & string>`.
`string` inside a template disables autocomplete
`` `on${string}` `` accepts any `on…` string, so editors will not list members. Prefer a closed union when the vocabulary is known.