📘
Template Literal Types: String Manipulation
Advanced
120 XP
45 min
Lesson Content
Template Literal Types
Template literal types allow you to manipulate string types at the type level, enabling powerful type-safe string operations.
Basic Template Literals
type Greeting = `Hello, ${string}!`;
let msg: Greeting = "Hello, World!"; // OK
// let msg2: Greeting = "Hi there"; // ErrorUnion in Template Literals
type EventName = `on${Capitalize<'click' | 'change'>}`;
// Result: 'onClick' | 'onChange'Utility Types with Strings
type Uppercase = // built-in
type Lowercase = // built-in
type Capitalize = // built-inExample Code
Understanding template literal type syntax
// Template literal types are compile-time
// For practice, simulate string manipulation
function createEventName(action: string): string {
return `on${action.charAt(0).toUpperCase() + action.slice(1)}`;
}
console.log(createEventName("click"));
console.log(createEventName("change"));Expected Output:
onClick onChange
Study Tips
- •Read the theory content thoroughly before practicing
- •Review the example code to understand key concepts
- •Proceed to the Practice tab when you're ready to code