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
- Template Literal Type Basics
- Modeling Structured Strings
- String Unions and Autocomplete
- Intrinsic String Manipulation Types