TypeScript Course
TypeScript
/
Advanced

Template Literal Types

Definition

Template literal types build on string literal types, allowing you to use string interpolation syntax (backticks and `${}`) to construct massive combinations of string types.

Explain Like I'm New

Imagine you have a grid with X axis ('top', 'bottom') and Y axis ('left', 'right'). Instead of manually typing all 4 combinations ('top-left', 'top-right'...), Template Literal Types let you mathematically multiply the two unions together to auto-generate all possible string combinations.

Real World Example

Typing CSS utility classes in a framework like Tailwind: `type Margin = 'm-${t|b|l|r}-${1|2|3|4}';`. This auto-generates `'m-t-1'`, `'m-b-3'`, etc.

Common Use Cases

  • •Typing string-based APIs
  • •CSS-in-JS libraries
  • •Event names (`on${EventName}`)

Interactive Example

type Vertical = "top" | "bottom";
type Horizontal = "left" | "right";

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

function placeElement(pos: Position) { ... }
placeElement("top-left"); // Valid
// placeElement("center"); // Error!


// Advanced: Auto-generating event handler types
type Entity = "User" | "Post";
// Generates: "onUserUpdate" | "onPostUpdate"
type UpdateEvents = `on${Entity}Update`;

Interview Questions

basic

  • What happens when you use `${}` with a Union type inside it?

intermediate

  • What are the built-in intrinsic string manipulation types?

advanced

  • How do you use Template Literals to remap keys in a Mapped Type?

Flash Cards

Question

What happens with a Union inside ${}?

Click to reveal answer
Answer

It performs a cross-product (Cartesian product). If you do `` `${'A'|'B'}-${1|2}` ``, it generates 4 strings: `'A-1' | 'A-2' | 'B-1' | 'B-2'`.

Question

What are intrinsic string types?

Click to reveal answer
Answer

TS provides built-in utilities: `Capitalize<T>`, `Uncapitalize<T>`, `Uppercase<T>`, and `Lowercase<T>`. Example: `Capitalize<'hello'>` outputs the type `'Hello'`.