Syntax
type Event = `${Field}Changed`;Examples
Structured Strings with Template Literal Types: working example
Run this standalone example after compiling with TypeScript 5.4+ in strict mode, targeting ES2022. Expected result: The program prints emailChanged; the commented phoneChanged call would be rejected.
type Field = "name" | "email";
type ChangeEvent = `${Field}Changed`;
function announce(event: ChangeEvent): string { return event; }
console.log(announce("emailChanged"));
// announce("phoneChanged"); // Type error.- Expected result: The program prints emailChanged; the commented phoneChanged call would be rejected.
- Interpolation distributes over the Field union to produce two allowed strings.
- The template syntax is in a type declaration, so it generates no string-building code.
Best practices
- Keep generated unions manageable; large cross-products slow checking and are hard to inspect.
- Validate strings received from networks or storage.
Runtime & versions
Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
TypeScript Handbook