What are Template Literal Types?
Introduced in TypeScript 4.1, Template Literal Types allow you to create new string literal types by concatenating other types together using the same syntax as JavaScript template strings (
${}).This enables you to model string patterns like CSS properties, event names, or URL routes directly in the type system.
1. Basic Usage
typescript
2. Union Distribution
When you use a union in a template literal, TypeScript generates every possible combination.
typescript
3. String Manipulation Utilities
TypeScript provides several built-in types to help with template literals:
Uppercase<S>Lowercase<S>Capitalize<S>Uncapitalize<S>
typescript
4. Real-World Use Case: Event Listeners
You can create a type that enforces a specific naming convention for events.
typescript
5. Key Remapping in Mapped Types
Template literals are often used to rename keys when creating a new object type.
typescript
Summary Checklist
- Use
${}to combine string literal types. - Unions inside literals create all possible combinations.
- Use
CapitalizeandUppercasefor string formatting. - Perfect for typed CSS, event emitters, and API endpoints.
- Essential for advanced "Key Remapping" patterns.