Template Literal Types
February 9, 20261 min readpart 06/20
Difficulty: Intermediate. Prerequisites: String literal types, union types, basic generics.
Template literal types bring string manipulation to the type level, allowing you to create new string literal types through concatenation and pattern matching. Combined with intrinsic types (Uppercase, Lowercase, Capitalize, Uncapitalize), they enable powerful string-based transformations for routes, events, and APIs.
Key concepts
- Creating string literal types with template syntax
- Intrinsic manipulation: Uppercase, Lowercase, Capitalize, Uncapitalize
- Pattern matching and extracting parts with infer
- Combining with unions for string permutations
- Building type-safe route parsers and event emitters
Example
type Greeting = `Hello, ${'world'}`; // "Hello, world"
// Union expansion
type Size = 'sm' | 'lg';
type Color = 'red' | 'blue';
type Combo = `${Color}-${Size}`; // "red-sm" | "red-lg" | "blue-sm" | "blue-lg"
// Intrinsic manipulation
type Upper = Uppercase<'hello'>; // "HELLO"
type Cap = Capitalize<'hello'>; // "Hello"
// Extract route params
type Params<T> = T extends `${string}:${infer P}/${infer R}` ? P | Params<R>
: T extends `${string}:${infer P}` ? P : never;
type P = Params<'/users/:id/posts/:pid'>; // "id" | "pid"
// Event handlers
type Handlers<T> = { [K in keyof T as `on${Capitalize<string & K>}`]: (e: T[K]) => void };
type H = Handlers<{ click: MouseEvent }>; // { onClick: (e: MouseEvent) => void }
// Split string
type Split<S extends string, D extends string> =
S extends `${infer H}${D}${infer T}` ? [H, ...Split<T, D>] : [S];
type Parts = Split<'a-b-c', '-'>; // ['a', 'b', 'c']
// Real-world: Hono extracts route params purely at the type level
type ParamKey<T> = T extends `:${infer P}` ? P : never;
type ParamKeys<Path> = Path extends `${infer Seg}/${infer Rest}`
? ParamKey<Seg> | ParamKeys<Rest> : ParamKey<Path>;
type R = ParamKeys<'/users/:id/posts/:pid'>; // 'id' | 'pid'Resources
- TypeScript Handbook - Template Literals: Official documentation
- Type-Level TypeScript: String manipulation chapter
Practice
- Template Literal Types (TypeHero, Medium)
- Capitalize (TypeHero, Easy)
- Trim (TypeHero, Medium)
- Replace (TypeHero, Medium)
- Trim Left (Type Challenges, Medium)
- Trim (Type Challenges, Medium)
- Capitalize (Type Challenges, Medium)
- Replace (Type Challenges, Medium)
- Drop Char (Type Challenges, Medium)
- Length of String (Type Challenges, Medium)
Hints
- Template literal types distribute over unions — each member of the union gets combined.
- Use infer inside template literals to extract parts of a string type.