Template literal types
Overview
You know string literal types: "sm" | "md" | "lg". Template literal types let you build string types, using the same backtick syntax as JavaScript template strings. They can combine unions into every possible combination, describe patterns like "12px" or "#ff0000", and even pull pieces out of strings.
Building string types
type Greeting = `hello ${string}`;
const a: Greeting = "hello world"; // ✓
const b: Greeting = "hi world";
// error TS2322: Type '"hi world"' is not assignable to type '`hello ${string}`'.Inside ${…} you can put string, number, bigint, boolean, literal types or unions.
Combinations
When the placeholders contain unions, the result is the union of every combination:
type Size = "sm" | "md" | "lg";
type Color = "red" | "blue";
type ButtonClass = `btn-${Size}-${Color}`;
// "btn-sm-red" | "btn-sm-blue" | "btn-md-red" | "btn-md-blue" | "btn-lg-red" | "btn-lg-blue"This is great for design tokens, CSS utility classes, translation keys and event names — and the editor autocompletes all of them. Be careful with very large unions: three placeholders with 20 options each make 8,000 members, which slows the checker down.
Patterns
string and number placeholders describe patterns rather than fixed values:
type Px = `${number}px`;
type HexColor = `#${string}`;
type UserId = `user_${number}`;
type DataAttribute = `data-${string}`;
const width: Px = "12.5px"; // ✓
const bad: Px = "12em";
// error TS2322: Type '"12em"' is not assignable to type '`${number}px`'.`${number}` accepts anything JavaScript’s Number() would parse as a number — "1.5", "1e3", "-2". `#${string}` only checks the # prefix, not that the rest is valid hex; for real validation you still need run-time checks.
Changing case
Four built-in types transform string literal types:
type A = Uppercase<"get">; // "GET"
type B = Lowercase<"POST">; // "post"
type C = Capitalize<"click">; // "Click"
type D = Uncapitalize<"Click">; // "click"
type Event = "click" | "focus" | "blur";
type Handler = `on${Capitalize<Event>}`; // "onClick" | "onFocus" | "onBlur"With key remapping in mapped types (Mapped types), this generates whole APIs:
type Handlers<T> = {
[K in keyof T as `on${Capitalize<string & K>}Change`]: (value: T[K]) => void;
};
type FormHandlers = Handlers<{ name: string; age: number }>;
// { onNameChange: (value: string) => void; onAgeChange: (value: number) => void }Parsing strings with infer
Template literal types work in conditional types too, and infer can capture parts of a string:
type Trim<S extends string> = S extends ` ${infer Rest}` ? Trim<Rest> : S;
type T1 = Trim<" hi">; // "hi"
type Domain<E> = E extends `${string}@${infer D}` ? D : never;
type T2 = Domain<"asha@example.com">; // "example.com"A practical example — getting the parameter names out of a route path:
type RouteParams<Path extends string> =
Path extends `${string}:${infer Param}/${infer Rest}`
? Param | RouteParams<`/${Rest}`>
: Path extends `${string}:${infer Param}`
? Param
: never;
type P = RouteParams<"/users/:userId/posts/:postId">; // "userId" | "postId"
function buildPath<Path extends string>(path: Path, params: Record<RouteParams<Path>, string>) { … }
buildPath("/users/:userId", { userId: "7" }); // ✓
buildPath("/users/:userId", {}); // ✗ userId is missingThe type calls itself recursively to find every :param. Web frameworks and routers use exactly this technique to type route parameters from the path string you write.
Template literal types and run-time values
As always, these types are erased. A function that accepts `${number}px` still receives an ordinary string at run time; if the value comes from user input, validate it. Where template literal types shine is in code you write: class names, routes, event names and keys that are now autocompleted and checked.
Remember: backticks work in types too. Use them to combine unions, to describe string patterns, and — with
infer— to take strings apart at the type level.
Typed routes and design tokens
(1) Define type Space = 0 | 1 | 2 | 4 | 8 and type Side = "t" | "b" | "l" | "r", and build a template literal type Margin from m, a Side, - and a Space (all 20 combinations, such as "mt-2") — write margin(token: Margin): string returning margin-top: 8px for "mt-2" (2 × 4px). (2) Write a type Px for strings that are a number followed by px, and px(value: Px): number. (3) Write type RouteParams<Path> that extracts :param names from a path string, so RouteParams<"/users/:userId/posts/:postId"> is "userId" | "postId", and buildPath<P extends string>(path: P, params: Record<RouteParams<P>, string | number>): string that replaces each :param. Print some results and show with // @ts-expect-error that margin("mx-2"), px("12em") and a missing route param are rejected.
// 1. Margin tokens
// 2. Px values
// 3. RouteParams and buildPath// 1. Margin tokens
type Space = 0 | 1 | 2 | 4 | 8;
type Side = "t" | "b" | "l" | "r";
type Margin = `m${Side}-${Space}`; // "mt-0" | "mt-1" | … (20 combinations)
const SIDES = { t: "top", b: "bottom", l: "left", r: "right" } as const;
function margin(token: Margin): string {
const [prefix, size] = token.split("-");
const side = SIDES[(prefix ?? "mt").slice(1) as Side];
return `margin-${side}: ${Number(size) * 4}px`;
}
// 2. Px values
type Px = `${number}px`;
function px(value: Px): number {
return Number.parseFloat(value);
}
// 3. RouteParams and buildPath
type RouteParams<Path extends string> =
Path extends `${string}:${infer Param}/${infer Rest}`
? Param | RouteParams<`/${Rest}`>
: Path extends `${string}:${infer Param}`
? Param
: never;
function buildPath<P extends string>(path: P, params: Record<RouteParams<P>, string | number>): string {
return path.replace(/:(\w+)/g, (_, name: string) => String((params as Record<string, string | number>)[name]));
}
console.log(margin("mt-2"), "|", margin("ml-8")); // margin-top: 8px | margin-left: 32px
console.log(px("12.5px") * 2); // 25
console.log(buildPath("/users/:userId/posts/:postId", { userId: 7, postId: "intro" })); // /users/7/posts/intro
type Check = RouteParams<"/users/:userId/posts/:postId">; // "userId" | "postId"
const param: Check = "postId";
console.log(param);
// @ts-expect-error -- "mx" is not a valid side
margin("mx-2");
// @ts-expect-error -- only px values allowed
px("12em");
// @ts-expect-error -- postId is missing
buildPath("/users/:userId/posts/:postId", { userId: 7 });Summary
- Template literal types use backtick syntax at the type level: `
get${Name}`. - With unions inside, they produce every combination: `
${Size}-${Color}`. - `
${number}pxand#${string}` describe string patterns, not just fixed strings. Uppercase,Lowercase,CapitalizeandUncapitalizechange the case of string literal types.- With
infer, template literals can parse strings at the type level — for example, route parameters.