Template Literal Types

Template literal types construct string literal types from other types. They can model event names, route patterns, CSS property names, and generated API keys. Combined with unions and mapped types, they allow type-safe relationships between names and values.

They are compile-time constraints, not string parsers at runtime. For dynamic strings from users or external services, validate the value at runtime even if a template literal type describes the expected pattern.

Type-safe event names
type Field = "name" | "email";
type ChangeEvent = `${Field}Changed`;
// "nameChanged" | "emailChanged"

function onChange(event: ChangeEvent) {
  console.log(event);
}
💡 TypeScript combines each member of Field with the suffix, producing a union of two valid event names.
Key Takeaways
  • Template literal types compose string literal types.
  • They can derive event names from domain keys.
  • Runtime strings still need validation at trust boundaries.
Knowledge Check

What is the resulting type of `${"get" | "set"}${"Name" | "Age"}`?