Template Literal Types
What
Template literal types allow you to create new literal types by combining existing types within a string template. They use the same backtick syntax as JavaScript template strings.
How
You can interpolate union types into a template string to automatically generate all possible combinations:
type Class = "wizard" | "warrior" | "rogue";
type Race = "elf" | "human" | "dwarf";
// Generates: "elf wizard" | "elf warrior" | "human wizard" | ...
type Hero = `${Race} ${Class}`;
// Enforce a pattern: string followed by a colon and a number
type LogRecord = `${string}: ${number}`;
const valid: LogRecord = "INFO: 200";
Why
Template literal types are incredibly powerful for enforcing string patterns (like CSS properties, localized keys, or structured log messages). They allow you to maintain strict type safety even for complex, dynamic string values.
Summary
While powerful, template literal types can quickly become complex, so they should be used when a specific string structure is critical to your application’s logic.