Course contentsShow
← TypeScript
Lesson 825 of 1,79619. Template Literal TypesFree lesson

Restricting String Shapes

Using template literals to enforce specific string formats at compile time, replacing runtime validation for known patterns.

Restricting String Shapes

You'll learn how to enforce specific string formats at compile time using template literal types, catching pattern violations before runtime.

The Core Idea

In JavaScript, you often validate string formats at runtime—checking if an email looks right, if a color starts with #, or if a URL matches a pattern. Template literal types let you move these validations to compile time for known patterns, making invalid strings a type error instead of a runtime surprise.

Think of it like a mold: instead of accepting any string and checking its shape later, you define the exact shape upfront. TypeScript won't let you pour the wrong shape into the mold.

How It Works

Template literal types can enforce specific patterns using literal strings and unions:

type HexColor = `#${string}`;

const validColor: HexColor = "#ff0000";   // ✓ Starts with #
const invalidColor: HexColor = "ff0000";  // ✗ Error: doesn't start with #

You can combine this with unions for multiple options:

type CSSUnit = `${number}px` | `${number}%` | `${number}em`;

const width: CSSUnit = "100px";     // ✓
const height: CSSUnit = "50%";      // ✓
const invalid: CSSUnit = "20";      // ✗ Error: missing unit
const wrong: CSSUnit = "20meters";  // ✗ Error: invalid unit

This replaces runtime validation for predictable patterns where you know the valid formats ahead of time. Instead of parsing and validating at runtime, TypeScript catches mismatches during development.

type EventName = `on${Capitalize<string>}`;

const clickHandler: EventName = "onClick";    // ✓
const hoverHandler: EventName = "onHover";    // ✓
const badHandler: EventName = "click";        // ✗ Error: must start with "on"

Key Takeaway: Template literal types turn string format requirements from runtime checks into compile-time guarantees, catching pattern violations before your code ever runs.