Learn the concept
Template Literal Types
Template literal types use the same syntax as template strings but operate on types. They can create union types from string combinations, validate string patterns, and transform string types. Useful for type-safe event names, CSS properties, and API routes.
Template Literal Syntax:
\${Type}``Intrinsic String Types:
Uppercase<T>: Convert to uppercaseLowercase<T>: Convert to lowercaseCapitalize<T>: Capitalize first letterUncapitalize<T>: Lowercase first letterUse Cases:
// Simple string combination
type Greeting = `Hello, ${string}!`;
const g1: Greeting = 'Hello, World!'; // OK
const g2: Greeting = 'Hi, World!'; // Error
// Union distribution
type Color = 'red' | 'blue' | 'green';
type Size = 'small' | 'large';
type ColorSize = `${Color}-${Size}`;
// 'red-small' | 'red-large' | 'blue-small' | 'blue-large' | 'green-small' | 'green-large'
// Event names pattern
type EventName = `on${Capitalize<'click' | 'hover' | 'focus'>}`;
// 'onClick' | 'onHover' | 'onFocus'
// Intrinsic string manipulation
type Upper = Uppercase<'hello'>; // 'HELLO'
type Lower = Lowercase<'HELLO'>; // 'hello'
type Cap = Capitalize<'hello'>; // 'Hello'
type Uncap = Uncapitalize<'Hello'>; // 'hello'Parsing URL patterns like /users/:id/posts/:postId into typed parameter objects at the type level
Creating type-safe CSS property names and value combinations using template literals
Auto-generating event handler names (onClick, onHover) from event name unions
Build a router where path parameters are extracted as types from route strings using template literal types
Create a type system for utility CSS classes (e.g., margin-${Direction}-${Size}) with full autocomplete