Summary: Lifting String Patterns to the Type Level
Template Literal Types fundamentally elevate structural string validation to the type level. Previously we'd use string types with runtime validation; now the type itself expresses the pattern.
Core Takeaways
- Union distribution:
${A}-${B}creates all combinations of A and B (like multiplication) - Uppercase/Lowercase/Capitalize/Uncapitalize: String manipulation at the type level
- Combined with Mapped Types: Transform property names while creating new types
- Real use cases: Event emitters, API routes, CSS classes, action creators
- Performance caution: Unions over 100 slow down,
numberis dangerous - Runtime is separate: Type checking ≠ runtime validation, external data still needs validation
When to Use
- Strings have clear patterns (
user:*,/api/*,on*Event) - Typo bugs actually happen frequently (event names, class names, routes)
- Unions can be limited to under 100
- Complexity is understandable to teammates
When NOT to Use
- Pattern is too flexible (plain
stringis better) - Union is infinite or over 1000 (TypeScript crashes)
- Trying to replace runtime validation (impossible)
- Type code exceeds 10 lines (over-abstraction)
Ultimately, I understood Template Literal Types as "regular expressions for the type system." Just as runtime regex validates strings, Template Literal Types validate string patterns at the type level. But not all regex is good, and not all Template Literal Types are useful. Balance between practicality and readability was the key lesson.