TypeScript Template Literal Types
JavaScript template literals build strings: `Hello ${name}`. TypeScript borrows the same backtick syntax at the type level. A template literal type builds new string literal types out of other types — and when you combine it with unions, TypeScript generates every combination automatically.
Basic syntax
type Size = "small" | "large";
type Color = "red" | "blue";
type ButtonClass = `btn-${Size}-${Color}`;
// "btn-small-red" | "btn-small-blue" | "btn-large-red" | "btn-large-blue"
const ok: ButtonClass = "btn-large-blue";
console.log(ok);
const all: ButtonClass[] = ["btn-small-red", "btn-small-blue", "btn-large-red", "btn-large-blue"];
console.log(all.length, "combinations");btn-large-blue
4 combinations
The union is expanded like a cross product: 2 sizes × 2 colors = 4 string literal types. A misspelled class name is now a compile error:
type Size = "small" | "large";
type Color = "red" | "blue";
type ButtonClass = `btn-${Size}-${Color}`;
const bad: ButtonClass = "btn-medium-red";
console.log(bad);main.ts(5,7): error TS2322: Type '"btn-medium-red"' is not assignable to type '"btn-small-red" | "btn-small-blue" | "btn-large-red" | "btn-large-blue"'.
Patterns with string and number
Placeholders don't have to be literal unions. Using string, number or bigint inside a template literal type describes a whole pattern of strings:
type Px = `${number}px`;
type CssVar = `--${string}`;
type Id = `user_${number}`;
const width: Px = "120px";
const accent: CssVar = "--accent-color";
const id: Id = "user_42";
function toNumber(value: Px): number {
return parseFloat(value);
}
console.log(width, accent, id);
console.log(toNumber("12.5px") * 2);120px --accent-color user_42
25
"12.5px" matches ${number}px, but "wide" or "12em" would not. This is a lightweight way to encode formats such as IDs, units or URL paths in the type system.
Intrinsic string manipulation types
TypeScript has four built-in helper types for changing the case of string literal types:
| Type | "helloWorld" becomes |
|---|---|
Uppercase<T> |
"HELLOWORLD" |
Lowercase<T> |
"helloworld" |
Capitalize<T> |
"HelloWorld" |
Uncapitalize<T> |
"helloWorld" |
They are mostly used together with template literal types to derive names:
type Field = "name" | "email" | "age";
type Getter = `get${Capitalize<Field>}`; // "getName" | "getEmail" | "getAge"
type ChangeEvent = `${Field}Changed`; // "nameChanged" | ...
type EnvKey = `APP_${Uppercase<Field>}`; // "APP_NAME" | ...
const g: Getter = "getEmail";
const e: ChangeEvent = "ageChanged";
const k: EnvKey = "APP_NAME";
console.log(g, e, k);getEmail ageChanged APP_NAME
Typing an event emitter
A realistic use: deriving event-handler names from a list of events. Combined with mapped types (covered later), you can build an object type whose keys are generated:
type Events = {
click: { x: number; y: number };
keypress: { key: string };
};
type Handlers = {
[E in keyof Events as `on${Capitalize<E>}`]: (payload: Events[E]) => void;
};
// { onClick: (payload: {x, y}) => void; onKeypress: (payload: {key}) => void }
const handlers: Handlers = {
onClick: (p) => console.log(`clicked at ${p.x},${p.y}`),
onKeypress: (p) => console.log(`pressed ${p.key}`),
};
handlers.onClick({ x: 10, y: 20 });
handlers.onKeypress({ key: "Enter" });clicked at 10,20
pressed Enter
Notice that p in each handler is typed correctly without any annotation — TypeScript computed the parameter type from the event name.
Extracting parts of a string with infer
Template literal types can also be used for matching. Inside a conditional type, infer captures the part of the string that a placeholder matched:
type RouteParam<S extends string> =
S extends `${string}:${infer Param}/${infer Rest}`
? Param | RouteParam<Rest>
: S extends `${string}:${infer Param}`
? Param
: never;
type Params = RouteParam<"/users/:userId/posts/:postId">; // "userId" | "postId"
function buildUrl(params: Record<Params, string>): string {
return `/users/${params.userId}/posts/${params.postId}`;
}
console.log(buildUrl({ userId: "7", postId: "99" }));/users/7/posts/99
This is the same trick that routing libraries use to give you typed URL parameters. Conditional types and infer get their own lesson later on.
Note: Template literal types exist only at compile time. To build the actual strings at runtime you still use ordinary JavaScript template literals.
Test yourself
How many members does ` {"x" | "y" | "z"} ` have?
- 2
- 3
- 5
- 6
Which string is assignable to ` ${number}px `?
- "px"
- "ten px"
- "3.5px"
- "3.5 px"
What is Capitalize<"save">?
- "SAVE"
- "Save"
- "save"
- string