Sub topic 10
Template literal types
Template literal types build new string types from existing ones. They use the same backtick and ${} syntax as JavaScript template strings, but they work on types. They let you derive a union such as "onClick" | "onFocus" from "click" | "focus" instead of writing every member by hand.
This chapter assumes you know string literal types, unions of literals, and as const. It also assumes you can read generic type aliases with extends conditions. The typeof and keyof operators should be familiar too.
The basic form
A template literal type looks like a template string, but every slot holds a type.
type Greeting = `Hello, ${string}`;
const a: Greeting = "Hello, Ada"; // OK
const b: Greeting = "Hi, Ada"; // Error: Type '"Hi, Ada"' is not assignable to type '`Hello, ${string}`'.Greeting is not a single literal. It describes every string that starts with Hello, . The ${string} slot accepts any text, including an empty string. So "Hello, " also matches.
The slot can hold string, number, bigint, boolean, null, undefined, or a literal or union of those. Other types, such as objects, are rejected.
type Px = `${number}px`;
const w: Px = "12px"; // OK
const h: Px = "1.5px"; // OK
const bad: Px = "wide px"; // ErrorThe ${number} slot accepts any text that JavaScript can read as a number. That includes "1e3", so "1e3px" is also a valid Px. The pattern checks the text format, not whether the number is sensible for your use.
Interpolating unions
When a slot holds a union, TypeScript produces one string literal for each member.
type EventName = "click" | "focus";
type Handler = `on${Capitalize<EventName>}`; // "onClick" | "onFocus"Capitalize is one of four built-in string helpers. They are called intrinsic types because the compiler implements them directly.
| Helper | Effect | Example result |
|---|---|---|
| `Uppercase<T>` | All characters to upper case | `"CLICK"` |
| `Lowercase<T>` | All characters to lower case | `"click"` |
| `Capitalize<T>` | First character to upper case | `"Click"` |
| `Uncapitalize<T>` | First character to lower case | `"click"` |
These helpers distribute over unions. Capitalize<"click" | "focus"> is "Click" | "Focus".
Several unions give a cross product
If a template has more than one union slot, TypeScript produces every combination.
type Axis = "x" | "y";
type Edge = "start" | "end";
type Position = `${Axis}-${Edge}`;
// "x-start" | "x-end" | "y-start" | "y-end"
const p: Position = "y-end"; // OKThe size of the result is the product of the slot sizes. Three slots of ten members each give 1,000 literals. TypeScript refuses to build a union above 100,000 members and reports an error, so keep the slots small.
Combining templates with the types you already know
Template literal types connect to the earlier topics in this tutorial. Here are the three combinations you will use most.
With a derived union
The constant-object pattern gives you a union of values. You can feed that union into a template.
const Status = {
Active: "active",
Inactive: "inactive",
} as const;
type Status = (typeof Status)[keyof typeof Status];
type StatusLabel = `status:${Status}`; // "status:active" | "status:inactive"With string enums
A string enum type can appear in a template slot. TypeScript uses the enum's string values.
enum Color {
Red = "RED",
Green = "GREEN",
}
type ColorClass = `text-${Lowercase<Color>}`; // "text-red" | "text-green"
const c: ColorClass = "text-red"; // OKThe result is a plain union of string literals, not an enum. That means "text-red" is accepted directly. The nominal-like restriction of enums does not carry over.
Template slots also work with numeric enums, but the result is the number rendered as text, such as "0" and "1". This is rarely what you want.
With mapped types and key remapping
A mapped type can rename keys with as. Combined with a template, it generates whole object shapes.
type Getters<T> = {
[K in keyof T & string as `get${Capitalize<K>}`]: () => T[K];
};
interface User {
name: string;
age: number;
}
type UserGetters = Getters<User>;
// { getName: () => string; getAge: () => number }
const g: UserGetters = {
getName: () => "Ada",
getAge: () => 36,
};The & string filter matters. keyof T can include number and symbol keys, and Capitalize only accepts strings. Without the filter, the compiler reports an error on Capitalize<K>.
Requiring complete coverage
Because a template produces a union, you can use that union as the key set of a Record. The compiler then requires one entry for each generated member.
type EventName = "click" | "focus";
type Handler = `on${Capitalize<EventName>}`;
const handlers: Record<Handler, () => void> = {
onClick: () => console.log("clicked"),
onFocus: () => console.log("focused"),
};If you later add "blur" to EventName, the handlers object fails to compile until you add onBlur. This gives you the same exhaustiveness guarantee as the never check in a switch, applied to an object.
Pattern matching with infer
A template literal type can also appear in the extends part of a conditional type. There you can use infer to capture the parts of a string.
type Split<S extends string, D extends string> =
S extends `${infer Head}${D}${infer Tail}`
? [Head, ...Split<Tail, D>]
: [S];
type Parts = Split<"a.b.c", ".">; // ["a", "b", "c"]Here is how the match works:
Headcaptures the shortest text before the firstD.Tailcaptures everything after it.- If
Ddoes not appear, the condition fails and the result is[S]. - The recursion ends when no delimiter remains.
When two infer slots sit next to each other with no separator, the first captures a single character and the second captures the rest. This is how you write types that walk through a string one character at a time.
You can also constrain what an infer slot captures. Since TypeScript 4.8, infer N extends number parses the captured text as a number.
type ToNumber<S extends string> = S extends `${infer N extends number}` ? N : never;
type Forty = ToNumber<"40">; // 40
type None = ToNumber<"abc">; // neverValue-level gotchas
Types are only half of the picture. When you write an actual template string in code, the result type is string by default.
const name = "click";
const plain = `on${name}`; // type: string
const exact = `on${name}` as const; // type: "onclick"The as const assertion tells the compiler to keep the template as a literal type. This only helps when every interpolated value has a literal type. A let variable or a string parameter gives you a plain string again, even with as const. This is the widening problem from earlier chapters in a new place.
A second gotcha is that string methods do not narrow. This check proves nothing to the compiler:
type ApiPath = `/api/${string}`;
function load(path: string): void {
if (path.startsWith("/api/")) {
// path is still string here
}
}To narrow, write a type guard. The is return type tells the compiler what a true result means.
type ApiPath = `/api/${string}`;
function isApiPath(path: string): path is ApiPath {
return path.startsWith("/api/");
}
function fetchPath(path: ApiPath): void {
console.log(`GET ${path}`);
}
function load(path: string): void {
if (isApiPath(path)) {
fetchPath(path); // OK: path is ApiPath here
}
}The compiler trusts your guard. If the runtime check is wrong, the type is wrong too, so keep the check and the type in sync.
Template types leave no runtime trace
Like unions of literals, and unlike enums, template literal types are erased during compilation. The compiled JavaScript has no object for Handler or Position. You cannot loop over the members at runtime. If you need the list at runtime, define a constant array with as const and derive the type from it.
const events = ["click", "focus"] as const;
type EventName = (typeof events)[number]; // "click" | "focus"
type Handler = `on${Capitalize<EventName>}`;
for (const e of events) {
console.log(e); // runtime access to the same list
}This keeps one source of truth. The array is the runtime value, and the types follow from it.
When to use template literal types
Use them when strings follow a naming rule that you want the compiler to enforce:
- Event handler names derived from event names.
- CSS class or unit patterns such as
${number}px. - Route prefixes like
/api/${string}. - Getter and setter names generated from property names.
Avoid them when the set of valid strings has no structure, or when the cross product is large. A plain union of literals is clearer there. If a value must come from a fixed set and you need runtime iteration, the as const array approach above is usually enough.
Exercise
Given type Size = "sm" | "lg"; type Tone = "light" | "dark"; type Theme = ${Size}-${Tone};, list every member of Theme. Then say what happens to the number of members if you add a third Tone value.
Show answer
Theme is "sm-light" | "sm-dark" | "lg-light" | "lg-dark". The count is the product of the two union sizes, 2 x 2 = 4. Adding a third Tone value makes it 2 x 3 = 6 members.
Exercise
Write a type Setters<T> that maps an object type to setter function names. For { name: string; age: number } it should give { setName: (value: string) => void; setAge: (value: number) => void }. Why is & string needed after keyof T?
Show answer
type Setters<T> = { [K in keyof T & string as set${Capitalize<K>}]: (value: T[K]) => void; }; The & string filter removes number and symbol keys from keyof T. Capitalize only accepts string types, so without the filter the compiler rejects Capitalize<K>.
Exercise
A function takes path: string, and you check it with path.startsWith("/api/"). Why can you not pass path to a function expecting ` /api/${string} ` afterward, and how do you fix it?
Show answer
startsWith returns a plain boolean, so the compiler does not narrow path and it stays string. Write a type guard such as function isApiPath(path: string): path is /api/${string}`, whose body does the startsWith check, and call it in the if`.