How to use template literal types
· Category: TypeScript
Short answer
Template literal types construct new string types by embedding other types inside a template string, similar to JavaScript template literals.
Steps
- Define a template type:
type Greeting =Hello, ${World};whereWorldis a string literal type. - Combine unions to produce every permutation:
type Color = 'red' | 'blue'; type EventName =on${Capitalize} ; - Use intrinsic string manipulation types:
Uppercase,Lowercase,Capitalize,Uncapitalize. - Validate string patterns at the type level.
- Combine with mapped types to generate property names.
Tips
- Template literal types are invaluable for typing CSS-in-JS, event names, and routing paths.
- Excessive permutations from large unions can hit the type instantiation depth limit.
Common issues
- Very large unions of template literals can degrade compiler performance.
- Recursive template literal types may require tail-recursion elimination flags in recent TypeScript versions.