TypeScript
/Advanced
Template Literal Types
Definition
Template literal types build on string literal types, allowing you to use string interpolation syntax (backticks and `${}`) to construct massive combinations of string types.
Explain Like I'm New
Imagine you have a grid with X axis ('top', 'bottom') and Y axis ('left', 'right'). Instead of manually typing all 4 combinations ('top-left', 'top-right'...), Template Literal Types let you mathematically multiply the two unions together to auto-generate all possible string combinations.
Real World Example
Typing CSS utility classes in a framework like Tailwind: `type Margin = 'm-${t|b|l|r}-${1|2|3|4}';`. This auto-generates `'m-t-1'`, `'m-b-3'`, etc.
Common Use Cases
- •Typing string-based APIs
- •CSS-in-JS libraries
- •Event names (`on${EventName}`)
Interactive Example
Loading Code Playground...
Interview Questions
basic
- What happens when you use `${}` with a Union type inside it?
intermediate
- What are the built-in intrinsic string manipulation types?
advanced
- How do you use Template Literals to remap keys in a Mapped Type?