TS Template Literal Types
Template literal types let you build string literal types by interpolation. Pair them with utility types (Uppercase, Capitalize, …) to derive type-safe strings.
Basics
TS
type Greeting = `Hello, ${string}!`;
const a: Greeting = 'Hello, Ada!'; // ✓
// const b: Greeting = 'Hi, Ada!'; // ✗ error
Union expansion
TS
type Side = 'top' | 'bottom';
type Axis = 'x' | 'y';
type Combination = `${Side}-${Axis}`;
// 'top-x' | 'top-y' | 'bottom-x' | 'bottom-y'
String manipulation utilities
| Utility | Effect |
|---|---|
Uppercase<S> | 'click' → 'CLICK' |
Lowercase<S> | 'CLICK' → 'click' |
Capitalize<S> | 'click' → 'Click' |
Uncapitalize<S> | 'Click' → 'click' |
Real-world: typed event names
TS
type EventName<T extends string> = `on${Capitalize<T>}`;
type OnClick = EventName<'click'>; // 'onClick'
type OnHover = EventName<'hover'>; // 'onHover'
API route types
TS
type Method = 'GET' | 'POST' | 'PUT' | 'DELETE';
type Route = '/users' | '/posts' | '/comments';
type ApiCall = `${Method} ${Route}`;
// 'GET /users' | 'POST /users' | ... — 12 combinations
Parsing — inference with infer
TS
type SplitFirst<S> = S extends `${infer Head}/${infer Tail}` ? Head : S;
type T = SplitFirst<'users/42/orders'>; // 'users'
Tip: Combine template literal types with mapped types to derive entire APIs (event handler props, route maps) from a small list of base strings. The pay-off: rename one and TS forces every consumer to update.
Example
Example
type Greeting = `Hello, ${string}!`;
const g: Greeting = 'Hello, Ada!';
type EventName<T extends string> = `on${Capitalize<T>}`;
type OnClick = EventName<'click'>; // 'onClick'
console.log(g);
Try it Yourself »
Exercise
Utility that uppercases the first letter.
type On<T extends string> = `on${
<T>}`;
PascalCase; 10 chars.
Discussion
Loading…