Template Literal Types
Template Literal Types — the core idea
Template literal types combine string literal unions into new string literal types. They provide precise contracts for event names, CSS-like settings, and repeated naming conventions without copying a long list of strings.
What you’ll learn
- Explain template literal types with a concrete use case.
- Run the example and account for every line of its output.
- Recognize the difference between compile-time checking and runtime behavior.
Understand the rules and when to use them
Reading the code: Capitalize maps each Action literal to Open or Close. The template type yields "onOpen" | "onClose". subscribe performs ordinary JavaScript string interpolation at runtime.
Keep the boundary clear: A template literal type does not create the event listeners; it only constrains accepted names.
See the idea as a flow
Run the complete TypeScript example
Save the code as template-literal-types.ts. The result below was captured after compiling this exact example with strict TypeScript checking and executing the emitted JavaScript in Node.js.
TypeScript code
type Action = "open" | "close";
type EventName = `on${Capitalize<Action>}`;
function subscribe(name: EventName): string { return `Subscribed: ${name}`; }
console.log(subscribe("onOpen"));
console.log(subscribe("onClose"));Verified output
Subscribed: onOpen
Subscribed: onCloseBuild: npx tsc --strict --target es2022 --module commonjs --lib es2022,dom,esnext.disposable template-literal-types.ts; run: node template-literal-types.js. The exact filename may be changed freely. When a multi-file project exists, prefer its tsconfig.json and build scripts.
Trace the example line by line
Capitalize maps each Action literal to Open or Close. The template type yields "onOpen" | "onClose". subscribe performs ordinary JavaScript string interpolation at runtime.
The output shown above comes from the initialized values in this program. Replacing a type annotation alone does not transform a JavaScript value.
Avoid this common mistake
A template literal type does not create the event listeners; it only constrains accepted names.
Check both the TypeScript diagnostic and the emitted JavaScript behavior. A program can compile correctly and still need runtime validation or error handling.
Practice independently
Introduce Action = "save" and call subscribe("onSave"). Try an invalid event such as "onDelete".
Before running your change, write down the type you expect TypeScript to infer and the output you expect JavaScript to print. Then check both predictions.
Check your understanding
What to remember
Template literal types combine string literal unions into new string literal types.
Try the practice change and re-run the exact program to test your understanding.
Reaching the recap and completing the quizzes are separate milestones.