Template literal types

Topic 6 of 6 in Type operators6 min readIntermediateFree course

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.

Template literal types. With type Size = “sm” | “lg” and type Color = “red” | “blue”, type ClassName = ${Size}-${Color} gives every combination: “sm-red” | “sm-blue” | “lg-red” | “lg-blue”. type Event = “click” | “focus”; type Handler = on${Capitalize<Event>} gives “onClick” | “onFocus”.

Building string types

TypeScript
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:

TypeScript
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:

TypeScript
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:

TypeScript
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:

TypeScript
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:

TypeScript
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:

TypeScript
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 missing

The 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.

Exercise

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.

TypeScript
// 1. Margin tokens

// 2. Px values

// 3. RouteParams and buildPath

Summary

  • Template literal types use backtick syntax at the type level: ` get${Name} `.
  • With unions inside, they produce every combination: ` ${Size}-${Color} `.
  • ` ${number}px and #${string} ` describe string patterns, not just fixed strings.
  • Uppercase, Lowercase, Capitalize and Uncapitalize change the case of string literal types.
  • With infer, template literals can parse strings at the type level — for example, route parameters.