Course contentsShow
← TypeScript
Lesson 827 of 1,79619. Template Literal TypesFree lesson

Template Literals in Generic Types

Using template literal types with type parameters to create reusable patterns that work across different string literal unions.

Template Literals in Generic Types

You'll learn: How to combine template literal types with type parameters to create flexible, reusable string transformation patterns.

What This Unlocks

Up until now, you've seen template literal types work with specific string literal unions. But what if you want to create a reusable type helper that can prefix, suffix, or transform any string union someone passes in? That's where generics meet template literals.

By using type parameters with template literal types, you can build powerful string transformation utilities that work across different inputs while maintaining full type safety.

The Core Pattern

The basic syntax combines everything you know:

type Prefix<T extends string> = `prefix_${T}`;

// Now you can reuse it with ANY string union:
type Colors = "red" | "blue" | "green";
type PrefixedColors = Prefix<Colors>;
// Result: "prefix_red" | "prefix_blue" | "prefix_green"

type Status = "active" | "inactive";
type PrefixedStatus = Prefix<Status>;
// Result: "prefix_active" | "prefix_inactive"

The T extends string constraint ensures you can only pass string types in, and the template literal ${T} distributes over unions automatically.

Practical Examples

You can create getters, setters, event names, or API endpoint patterns:

type MakeGetter<T extends string> = `get${Capitalize<T>}`;
type MakeSetter<T extends string> = `set${Capitalize<T>}`;

type Props = "name" | "age";
type Getters = MakeGetter<Props>; // "getName" | "getAge"
type Setters = MakeSetter<Props>; // "setName" | "setAge"

type OnEvent<T extends string> = `on${Capitalize<T>}`;
type Events = OnEvent<"click" | "hover">; 
// "onClick" | "onHover"

Key Takeaway: Template literals in generic types let you create reusable string transformation patterns that distribute over any union you pass in, making type-level string manipulation both powerful and flexible.