Advanced · 4 of 12 · 15 min read
Template literal types
String interpolation in the type system — how a union inside a template multiplies out, the four intrinsic case utilities, and parsing a string with infer.
- Template literal types
A template literal type uses the same backtick syntax as a template string, in type position. It turns “a string that looks like this” from a comment into something the compiler enforces.
The basics
type Greeting = `Hello, ${string}`;
const a: Greeting = "Hello, Ana";
// const b: Greeting = "Goodbye"; // not assignable
type Version = `${number}.${number}.${number}`;
const v: Version = "1.2.3";
// const w: Version = "1.2"; // not assignable
console.log(a, v);
${string} and ${number} accept any string or numeric segment. That already types things
that used to be a plain string with a hopeful name: a semver, a hex colour, a route, an id with
a prefix.
type Hex = `#${string}`;
type Route = `/${string}`;
type UserId = `user_${string}`;
const colour: Hex = "#aabbcc";
const route: Route = "/users/1";
const id: UserId = "user_42";
console.log(colour, route, id);
The check is shape-only — "#zzz" passes Hex — so it catches the wrong kind of string, not an
invalid one. For real validation, a branded type and a runtime check are still needed.
Unions multiply
type Size = "small" | "large";
type Colour = "red" | "blue";
type Variant = `${Size}-${Colour}`;
// "small-red" | "small-blue" | "large-red" | "large-blue"
const v: Variant = "large-blue";
console.log(v);
Four members from two by two. Useful at this scale, and the reason a template over two large unions can hang the compiler: it is a cross product, computed eagerly.
type Side = "top" | "right" | "bottom" | "left";
type Property = "margin" | "padding";
type Spacing = `${Property}-${Side}`; // 8 members
type Css = { [K in Spacing]?: string };
const css: Css = { "margin-top": "4px", "padding-left": "8px" };
console.log(css["margin-top"]);
The four intrinsics
type Loud = Uppercase<"hello">; // "HELLO"
type Quiet = Lowercase<"HELLO">; // "hello"
type Title = Capitalize<"hello">; // "Hello"
type Plain = Uncapitalize<"Hello">; // "hello"
const loud: Loud = "HELLO";
const title: Title = "Hello";
console.log(loud, title);
They are implemented in the compiler rather than in TypeScript, which is why there is no
Reverse<"abc"> or Trim in the standard library — those have to be written with recursive
infer. They distribute over a union, like everything else:
type Method = Uppercase<"get" | "post">; // "GET" | "POST"
const m: Method = "POST";
console.log(m);
| Utility | "hello world" becomes |
|---|---|
Uppercase<T> |
"HELLO WORLD" |
Lowercase<T> |
"hello world" |
Capitalize<T> |
"Hello world" |
Uncapitalize<T> |
"hello world" |
With key remapping
This is where template literals do their most useful everyday work:
interface User { name: string; age: number }
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
type Setters<T> = {
[K in keyof T as `set${Capitalize<string & K>}`]: (value: T[K]) => void;
};
type Accessors = Getters<User> & Setters<User>;
const accessors: Accessors = {
getName: () => "Ana",
getAge: () => 30,
setName: (value) => console.log(value),
setAge: (value) => console.log(value),
};
console.log(accessors.getName());
The string & K intersection is required: keyof T can include number and symbol, and the
case utilities only take strings.
Parsing with infer
A template literal in an extends clause is a pattern, so infer pulls the pieces out:
type Split<S extends string, Sep extends string> =
S extends `${infer Head}${Sep}${infer Tail}`
? [Head, ...Split<Tail, Sep>]
: [S];
type A = Split<"a.b.c", ".">; // ["a", "b", "c"]
type B = Split<"2026-11-25", "-">; // ["2026", "11", "25"]
const a: A = ["a", "b", "c"];
console.log(a);
The recursion is the same head/tail shape as on a tuple, with the base case being “the separator is not there any more”. From that, a path-aware lookup follows:
type Get<T, Path extends string> =
Path extends `${infer Key}.${infer Rest}`
? Key extends keyof T
? Get<T[Key], Rest>
: never
: Path extends keyof T
? T[Path]
: never;
interface Config { server: { host: string; port: number } }
type A = Get<Config, "server.host">; // string
type B = Get<Config, "server.nope">; // never
const a: A = "localhost";
console.log(a);
That is the type behind a get(obj, "a.b.c") helper, and the reason such helpers can return the
right type instead of any.
Trimming is the other classic:
type TrimLeft<S extends string> = S extends ` ${infer Rest}` ? TrimLeft<Rest> : S;
type TrimRight<S extends string> = S extends `${infer Rest} ` ? TrimRight<Rest> : S;
type Trim<S extends string> = TrimLeft<TrimRight<S>>;
type A = Trim<" hello ">; // "hello"
const a: A = "hello";
console.log(a);
Generating keys for an event map
type Events = "click" | "focus" | "blur";
type Listener = `on${Capitalize<Events>}`; // "onClick" | "onFocus" | "onBlur"
type Remover = `off${Capitalize<Events>}`;
type Emitter = { [K in Listener | Remover]: (handler: () => void) => void };
declare const emitter: Emitter;
emitter.onClick(() => console.log("clicked"));
emitter.offBlur(() => {});
console.log(typeof emitter.onFocus);
Add "keydown" to Events and six new methods appear on Emitter, all of them checked. That is
the payoff: one source of truth for a set of names that would otherwise be written three times.
Where it gets expensive
type Letter = "a" | "b" | "c" | "d" | "e";
type Two = `${Letter}${Letter}`; // 25
type Three = `${Letter}${Letter}${Letter}`; // 125
const t: Three = "abc";
console.log(t);
Each segment multiplies. A union of 100 keys crossed with 10 prefixes is 1000 literals, which is
fine; crossed with each other twice it is 10 million, which is not. When a template is slow, the
fix is almost always to stop enumerating and accept ${string} for the free part.
Common mistakes
Treating the check as validation
Mistake. Declaring Email as a template over ${string}@${string} and calling it validated.
Why it fails. "@" satisfies it. The pattern only constrains the shape, not the content.
What to do instead. Use it as a hint, and brand the type after a real runtime check.
Using keyof T in a case utility
Mistake. `get${Capitalize<K>}` where K comes from keyof T.
Why it fails. keyof T is string | number | symbol; Capitalize only accepts string.
What to do instead. Capitalize<string & K>.
Crossing two large unions
Mistake. A template over two 100-member unions “to be thorough”.
Why it fails. 10 000 literals get materialised, and the editor becomes unusable.
What to do instead. Enumerate one side and leave the other as ${string}, or narrow the
unions to what is actually used.
Check yourself
3 questions from the bank on what you just read. Answering here does not affect your quiz history.
A template literal type builds string literal types, and distributes over unions.
What is Event here?
type Entity = "user" | "order";
type Action = "created" | "deleted";
type Event = `${Entity}:${Action}`;What can infer do inside a template literal type?
What are Uppercase, Capitalize and friends?
Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.