🧵 TypeScript – Template Literal Types: Explained with Examples
🧲 Introduction – What Are Template Literal Types in TypeScript?
Introduced in TypeScript 4.1, Template Literal Types enable developers to construct new string literal types by combining string unions with template expressions. Just like template strings in JavaScript (Hello ${name}
), you can now build type-safe, dynamic string types.
🎯 In this guide, you’ll learn:
- What template literal types are and how they work
- How to use them with unions, generics, and
keyof
- Practical examples and real-world use cases
- How to combine them with utility types like
Capitalize
andLowercase
📘 What Are Template Literal Types?
Template Literal Types let you build string types by embedding types into a template string syntax.
📌 Syntax:
type Greeting = `Hello, ${string}`;
This creates a string literal type where any string
can be interpolated after "Hello, "
.
🧪 Example 1: Simple Template Literal Type
type UserId = `user_${number}`;
🔍 Explanation:
- This defines a type like
"user_1"
,"user_42"
,"user_999"
, etc. - TypeScript understands that anything matching this pattern is a valid
UserId
.
🎯 Example 2: Combine Unions to Form New Strings
type Roles = "admin" | "editor";
type Permission = "read" | "write";
type RolePermission = `${Roles}_${Permission}`;
// Result: "admin_read" | "admin_write" | "editor_read" | "editor_write"
🔍 Explanation:
- By combining two union types with template syntax, you create all possible string combinations.
- Useful for permissions, events, CSS class names, etc.
🔁 Example 3: Dynamic Keys in Object Types
type Events = "click" | "hover" | "focus";
type EventHandlerProps = {
[K in Events as `on${Capitalize<K>}`]: () => void;
};
// Resulting type:
{
onClick: () => void;
onHover: () => void;
onFocus: () => void;
}
🔍 Explanation:
- We’re remapping keys using template literals (
on${...}
). Capitalize
converts the first letter of each event to uppercase.- This is helpful when defining props in React components or DOM event handlers.
🧠 Example 4: Combining with Generics
type EventName<T extends string> = `on${Capitalize<T>}`;
type ClickEvent = EventName<"click">; // "onClick"
type HoverEvent = EventName<"hover">; // "onHover"
🔍 Explanation:
EventName
is a reusable generic type that generates event names based on a given string.Capitalize
makes the type output conform to camelCase naming conventions.
💡 Example 5: Enforcing Naming Conventions
type ComponentName = "home" | "login";
type ComponentFile = `${ComponentName}.component.ts`;
// Acceptable values: "home.component.ts" | "login.component.ts"
📌 This is a great way to enforce consistent file naming conventions within your team.
🧪 Utility Types That Pair with Template Literals
TypeScript provides several string manipulation utility types that work perfectly with template literals:
Utility | Description |
---|---|
Capitalize | Capitalizes first letter |
Uncapitalize | Makes first letter lowercase |
Uppercase | Converts entire string to uppercase |
Lowercase | Converts entire string to lowercase |
Example:
type Header = "title";
type CapitalHeader = Capitalize<Header>; // "Title"
type LowercaseHeader = Lowercase<"WELCOME">; // "welcome"
🧰 Real-World Use Cases for Template Literal Types
Use Case | Example |
---|---|
Dynamic event handlers | onClick , onMouseOver |
Role-based permissions | "admin_write" , "user_read" |
File naming conventions | "user.service.ts" , "app.module.ts" |
Tailwind-style class names | "text-red-500" |
Constructing route paths | "/user/:id" → RoutePath<"user"> |
⚠️ Limitations of Template Literal Types
- Cannot currently pattern match at runtime (compile-time only)
- Not intended for parsing complex string formats
- Works best with narrow string types (unions, not just
string
)
📌 Summary – Recap & Real-World Relevance
Template Literal Types are a powerful addition to TypeScript that allow developers to create dynamic, pattern-based string types. They enhance readability, maintainability, and prevent bugs through compile-time enforcement of string patterns.
🔍 Key Takeaways:
- Use backticks (`) with
${}
to combine types into strings - Combine with
keyof
,union
, and utility types likeCapitalize
- Enable dynamic string type creation based on logic
- Excellent for naming conventions, event systems, and UI props
⚙️ Real-world applications:
- Dynamic component props (e.g.,
onClick
,onHover
) - API route identifiers and tags
- Auto-generated class names and labels
- File or folder naming enforcement
❓ FAQs
❓ What are Template Literal Types in TypeScript?
✅ A type-level feature that lets you use ${}
inside backtick strings to create new string literal types.
❓ Can I combine template literal types with keyof
?
✅ Yes, and it’s extremely powerful. You can remap keys like this:
type Props<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
❓ What is the difference between string literals and template literals?
- A string literal is a fixed string like
"home"
. - A template literal type allows dynamic generation like
`user_${string}`
.
❓ Can template literal types enforce file naming?
✅ Yes. For example:
type ValidFile = `${string}.component.ts`;
Only file names ending in .component.ts
would be valid for this type.
❓ Are template literal types only for strings?
✅ Yes. They work only with string types and unions of string literals.
Share Now :