Codectionary / Developer documentation / TypeScript

Structured Strings with Template Literal Types

Template literal types construct string types by interpolating literal unions. They can describe event names or localized keys and reject misspellings at compile time. Introduced in TypeScript 4.1, they are type-level constraints and do not check arbitrary runtime strings automatically.

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.
  1. Expected result: The program prints emailChanged; the commented phoneChanged call would be rejected.
  2. Interpolation distributes over the Field union to produce two allowed strings.
  3. 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

Specifications & further reading