Template literal types

Advanced · 12 min

Building string types with backtick syntax, generating unions from combinations, and pulling strings apart with `infer`.

Before thisUnion and literal typesThe infer keyword

Typed Rocks · 12 min

Template literal types

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Typed RocksReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A template literal type uses the same backtick syntax as a JavaScript template string, but builds a string type from other types instead of a string value from other values.
  • Interpolating a union produces every combination, so two placeholders with two and three members give a union of six strings.
  • Placeholders can hold wide types such as `${number}` or `${string}`, which makes the template a pattern, like `${number}px`, rather than a fixed list.
  • The built-in `Uppercase`, `Lowercase`, `Capitalize` and `Uncapitalize` transform string literal types, which is how names like `onClick` are derived from `click`.
  • Inside a conditional type, `infer` in a template's placeholders splits a string: `` T extends `${infer A}/${infer B}` `` puts the text before the first `/` in `A` and the rest in `B`.
  • Combinations multiply, and TypeScript rejects a union that grows to around 100,000 members with an error saying it is too complex to represent.

Strings with structure

A lot of strings in real code follow a format. CSS sizes look like "12px". Event handler props are on plus a capitalised event name. API routes look like "/users/:id". Cache keys might be "user:42". Typing these as string lets any typo through, and literal unions only work when you can list every value by hand.

Template literal types, added in TypeScript 4.1, let you describe the format itself. They use the backtick syntax you already know from JavaScript, but at the type level.

Building strings from types

In a type position, a template string combines types instead of values:

type Greeting = `hello ${"world" | "there"}`; // "hello world" | "hello there"

type Vertical = "top" | "bottom";
type Horizontal = "left" | "right";
type Corner = `${Vertical}-${Horizontal}`;
// "top-left" | "top-right" | "bottom-left" | "bottom-right"

When a placeholder holds a union, the result covers every member. With two placeholders, you get every combination, like the rows of a multiplication table. That’s a compact way to describe a family of strings from a few small lists, and it stays in sync: add "center" to Horizontal and Corner grows to six members.

Patterns, not just lists

A placeholder doesn’t need a literal. It can hold string, number, bigint or boolean, and then the template describes a pattern:

type Pixels = `${number}px`;

const a: Pixels = "12px";
const b: Pixels = "1.5px";
const c: Pixels = "px"; // Error: Type '"px"' is not assignable to type '`${number}px`'.

type UserKey = `user:${string}`;
const key: UserKey = "user:42";
const wrong: UserKey = "account:42"; // Error: Type '"account:42"' is not assignable to type '`user:${string}`'.

`${number}px` accepts any string that is a valid number followed by px, which is infinitely many strings. No union could list them.

Changing case

Formats often need a word in a different case. TypeScript ships four intrinsic helpers that work on string literal types: Uppercase, Lowercase, Capitalize and Uncapitalize.

type EventName = "click" | "focus" | "blur";
type HandlerName = `on${Capitalize<EventName>}`; // "onClick" | "onFocus" | "onBlur"

type Shout = Uppercase<"stop">; // "STOP"

These are built into the compiler rather than written in TypeScript, because there’s no way to change a character’s case using conditionals alone.

Combined with key remapping in mapped types, this generates whole object types from a list of names:

type Handlers = {
  [E in EventName as `on${Capitalize<E>}`]: (event: Event) => void;
};

const handlers: Handlers = {
  onClick: () => {},
  onFocus: () => {},
  onBlur: () => {},
};

Taking strings apart with infer

Template literals also work as patterns on the right of extends in a conditional type. Put infer in a placeholder and TypeScript fills it with the matching part of the string:

type Head<T extends string> = T extends `${infer H}/${string}` ? H : T;

type H1 = Head<"users/42/posts">; // "users"
type H2 = Head<"users">; // "users"

type EventFromHandler<T> = T extends `on${infer E}` ? Uncapitalize<E> : never;
type EF = EventFromHandler<"onClick">; // "click"

A placeholder followed by literal text matches up to the first occurrence of that text. In Head, H gets everything before the first /. In EventFromHandler, the literal on has to come first, and E takes the rest.

An inferred placeholder can carry a constraint, and with number it converts the text into a number literal type:

type ToNumber<T> = T extends `${infer N extends number}` ? N : never;

type N1 = ToNumber<"42">; // 42
type N2 = ToNumber<"abc">; // never

Taking one piece off a string is half the job. Pulling every parameter out of a route like "/users/:id/posts/:postId" means repeating the match on what’s left, which is recursion. That’s the next lesson, recursive types.

Watch the multiplication

Combinations grow fast. Two placeholders with ten members each give 100 strings. Five placeholders that each hold the ten digits give 100,000, and at around that size TypeScript gives up with “Expression produces a union type that is too complex to represent.” Even well below that, huge unions make the editor slow. When a format really has that many values, a wide placeholder like ${number} is the better tool.

About the video

The Typed Rocks video follows the same arc as this lesson in about twelve minutes. Despite the title saying “Template Literals,” it is about the type-level feature: narrowing string types with templates, generating unions from combinations, and extracting parts of a string with infer. Watch it after the “building strings” and “patterns” sections, and return to the infer part once the conditional-type examples above make sense. Flo Woelki’s video, linked below, is a gentler start that covers the case helpers in more detail, and Harry Wolff’s longer exploration dates from shortly after the feature shipped.

Check yourself

  1. 01What is `` `${"top" | "bottom"}-${"left" | "right"}` ``?

    The union of all four combinations: `"top-left" | "top-right" | "bottom-left" | "bottom-right"`. Each placeholder holding a union multiplies the number of results.

  2. 02Which of `"12px"`, `"1.5px"` and `"px"` are assignable to `` `${number}px` ``, and why?

    `"12px"` and `"1.5px"` are, because their prefixes are valid numbers followed by `px`. `"px"` is not, because the empty string before `px` is not a number.

  3. 03How would you turn the union `"click" | "focus"` into `"onClick" | "onFocus"`?

    Write `` `on${Capitalize<E>}` `` with `E` set to that union. `Capitalize` upper-cases the first letter of each member, and the template distributes over the union to give one name per event.

  4. 04Given `type Head<T> = T extends `${infer H}/${string}` ? H : T`, what is `Head<"users/42/posts">`?

    `"users"`. A placeholder followed by literal text matches up to the first occurrence of that text, so `H` takes everything before the first `/`.

  5. 05Why might a template literal type built from several unions fail with 'Expression produces a union type that is too complex to represent'?

    Every placeholder holding a union multiplies the size of the result, and TypeScript refuses unions that reach about 100,000 members. Five placeholders that each hold the ten digits already produce 100,000 strings.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark