What are template literal types in TypeScript?

AdvancedTypeScript interview questionBy , updated 21 November 2026

Short answer

A template literal type uses the backtick syntax of JavaScript template strings at the type level: `${A}-${B}` is the type of every string made of an A, a dash and a B. When A or B is a union, the result is the union of every combination. With Capitalize and the other intrinsic types, infer and key remapping, they generate and parse string types such as event handler names and route params.

Building string types

Inside the ${} slots you can put string, number, bigint, boolean, null and undefined types, including literals and unions of them.

type Greeting = `hello ${string}`; // any string starting with "hello "
type Pixels = `${number}px`;

const a: Pixels = "12px"; // ok
const b: Pixels = "1.5px"; // ok
const c: Pixels = "12 px"; // error
const d: Pixels = "px"; // error

${string} and ${number} act as wildcards, so the result is a pattern rather than a fixed list. This is useful for typed CSS values:

type Unit = "px" | "rem" | "%";
type Length = `${number}${Unit}` | "auto";

function setWidth(el: HTMLElement, width: Length) {
  el.style.width = width;
}
setWidth(div, "50%"); // ok
setWidth(div, "50"); // error: no unit

Unions expand to every combination

When a slot holds a union, TypeScript produces the cartesian product: one member for each combination.

type Size = "sm" | "md" | "lg";
type Tone = "primary" | "danger";

type ButtonClass = `btn-${Size}-${Tone}`;
// "btn-sm-primary" | "btn-sm-danger" | "btn-md-primary" | ... (6 members)

The size multiplies with each slot, so a few large unions can produce a huge type. TypeScript reports an error when a union becomes too complex to represent, and large unions also slow down the type checker.

The intrinsic string types

TypeScript has four built-in types that change the case of string literal types: Uppercase, Lowercase, Capitalize (first character only) and Uncapitalize. They are implemented inside the compiler, not written in TypeScript, and they ignore locale.

type EventType = "click" | "keydown";
type Handler = `on${Capitalize<EventType>}`; // "onClick" | "onKeydown"
type Shout = Uppercase<"save">; // "SAVE"

Each one distributes over a union, as the example shows. Practise writing your own in Implement FirstChar, LastChar and Capitalize with template literal types.

Parsing strings with infer

In a conditional type, a template literal can be a pattern, and infer captures the parts that match.

type EventName<H> = H extends `on${infer E}` ? Uncapitalize<E> : never;
type E1 = EventName<"onClick">; // "click"

type Port<S> = S extends `${string}:${infer P extends number}` ? P : never;
type P1 = Port<"localhost:3000">; // 3000, a number literal

The matching rules are worth knowing. An infer placeholder followed by literal text matches up to the first occurrence of that text. An infer placeholder followed directly by another placeholder matches exactly one character. The last placeholder takes the rest. The infer P extends number form, added in TypeScript 4.8, converts the matched text into a number literal type.

With recursion, this is enough to extract typed route params:

type Params<Path extends string> =
  Path extends `${string}:${infer Name}/${infer Rest}`
    ? Name | Params<`/${Rest}`>
    : Path extends `${string}:${infer Name}`
      ? Name
      : never;

type RouteParams<Path extends string> = { [K in Params<Path>]: string };

type R = RouteParams<"/users/:id/posts/:postId">;
// { id: string; postId: string }

Build it yourself in Extract typed route params from a path pattern, and try Split, StringToTuple and LengthOfString for more recursion.

Key remapping with as

In a mapped type, an as clause can rename each key, and template literal types supply the new name. This is how libraries type getters, setters and event handler props.

type Getters<T> = {
  [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
type UserGetters = Getters<{ name: string; age: number }>;
// { getName: () => string; getAge: () => number }

type EventMap = { click: MouseEvent; keydown: KeyboardEvent };
type HandlerProps = {
  [K in keyof EventMap as `on${Capitalize<K>}`]?: (event: EventMap[K]) => void;
};
// { onClick?: (event: MouseEvent) => void; onKeydown?: (event: KeyboardEvent) => void }

string & K is needed in the generic Getters, because keyof T can include number and symbol keys and Capitalize only accepts strings. In HandlerProps the keys are known to be strings, so it is not needed. Practise this in Remap keys: prefix every key, build getters, and pick keys by value type and Convert between camelCase, snake_case and kebab-case at the type level.

Common follow-up questions

Do template literal types check strings at runtime?

No. Like all types, they are erased. They check string literals and values the compiler can see. A string from user input or an API is not assignable to `${number}px` until you narrow it, for example with a type guard that tests a regular expression.

Why is my variable not assignable to the template literal type?

A let declaration or an object property widens "12px" to string, and string does not match the pattern. Use const, an explicit type annotation, or as const to keep the literal type.

What is the difference between a template literal type and a tagged template?

A template literal type exists only at compile time and describes a set of strings. A tagged template, such as html`<p>${name}</p>`, is a runtime function call that receives the string parts and values.

How do template literal types relate to keyof?

They often consume it. `on${Capitalize<keyof EventMap & string>}` turns an object's keys into handler names. See keyof and typeof in TypeScript.

Mistakes to avoid

  • Forgetting string & K when building names from keyof T in a generic type

  • Multiplying several large unions and slowing the checker, or hitting the "too complex to represent" error

  • Writing infer N without extends number and expecting a number

    It captures text, so "3000" stays a string literal type.

  • Assuming Capitalize handles whole words

    It changes only the first character.

  • Writing deep recursive string parsers for app code where a plain union of literals would be clearer

Practise it in code

Interviewers rarely stop at the definition. These questions open in an editor with tests.

  1. Implement FirstChar, LastChar and Capitalize with template literal typesEasy18 min
  2. Extract typed route params from a path pattern like "/users/:id/posts/:postId"Hard50 min
  3. Remap keys: prefix every key, build getters, and pick keys by value typeMedium30 min
  4. Convert between camelCase, snake_case and kebab-case at the type levelMedium40 min
  5. Implement Split, StringToTuple and LengthOfStringMedium35 min