0Pricing
TypeScript Academy · Lesson

Modeling Structured Strings

Enforce formats like event names and route paths.

Enforcing String Formats

Many strings in real apps follow a structure: event handler names, API route paths, CSS variables. Template literal types let you model these formats so the compiler enforces them.

Modeling Event Handler Names

A handler name often looks like on plus a capitalized event. Using the intrinsic Capitalize helper inside a template, the event 'click' maps to the handler name 'onClick'.

type Event = "click" | "focus"
// template: on followed by Capitalize of Event
// => "onClick" | "onFocus"
const h: "onClick" | "onFocus" = "onClick"
console.log(h)

All lessons in this course

  1. Template Literal Type Basics
  2. Modeling Structured Strings
  3. String Unions and Autocomplete
  4. Intrinsic String Manipulation Types
← Back to TypeScript Academy