JavaScript and TypeScript course ยท Module 10: TypeScript in Practice
Template Literal Types - String Manipulation in Types
In this lesson3
Imagine a DNA sample labeling system in which every name follows the format dna-species-number. A plain string lets every typo through, and writing out all the variants by hand would take weeks. Template literal types are a TypeScript 4.1+ feature that lets you build string types with the template literal syntax from JavaScript. The compiler then checks the format of a string before the code reaches the lab.
Template Literal Types Basics
Basic Syntax
The notation looks like a regular template literal, but a type stands in place of a value: ${string} means any string, and ${number} any number written as text:
// Basic template literal types
type Greeting = `Hello ${string}`;
type Welcome = `Welcome to ${string}!`;
// Usage examples
const greeting1: Greeting = "Hello World"; // OK
const greeting2: Greeting = "Hello TypeScript"; // OK
// const greeting3: Greeting = "Hi World"; // Error! Must start with "Hello "
// Combining literal types
type EventName = "click" | "focus" | "blur";
type EventHandler = `on${Capitalize<EventName>}`;
// type EventHandler = "onClick" | "onFocus" | "onBlur"
// Practical example - CSS units
type CSSUnit = "px" | "%" | "em" | "rem" | "vh" | "vw";
type CSSValue = `${number}${CSSUnit}`;
const width: CSSValue = "100px"; // OK
const height: CSSValue = "50vh"; // OK
const margin: CSSValue = "2rem"; // OK
// const padding: CSSValue = "10"; // Error! Missing unit
// Nested template literals
type BreakpointSize = "sm" | "md" | "lg" | "xl";
type Breakpoint = `@${BreakpointSize}`;
type ResponsiveProp<T extends string> = T | `${T}${Breakpoint}`;
type Display = ResponsiveProp<"block" | "none" | "flex">;
// "block" | "none" | "flex" | "block@sm" | "none@sm" | "flex@sm" |Greeting accepts every string starting with Hello , not literally the text with a dollar sign. When you insert a union, TypeScript generates a union of all combinations, so EventHandler is three names, and Display as many as fifteen variants.
Pattern Matching with Template Literal Types
Combined with conditional types and the infer keyword, they let you take strings apart, much like a regular expression, only at compile time:
// Extracting parts of strings
type ExtractId<T> = T extends `id-${infer Id}` ? Id : never;
type UserId = ExtractId<"id-123">; // "123"
type PostId = ExtractId<"id-abc-def">; // "abc-def"
type Invalid = ExtractId<"user-123">; // never
// More complex pattern matching
type ParseRoute<T> = T extends `/${infer Module}/${infer Action}`
? { module: Module; action: Action }
: never;
type Route1 = ParseRoute<"/users/create">; // { module: "users"; action: "create" }
type Route2 = ParseRoute<"/posts/edit">; // { module: "posts"; action: "edit" }
// Recursive parsing
type Split<S extends string, D extends string> =
S extends `${infer T}${D}${infer U}`
? [T, ...Split<U, D>]
: [S];
type PathSegments = Split<"users/123/posts/456", "/">;
// ["users", "123", "posts", "456"]
// Extracting parameters from URL
type ExtractParams<T extends string> = T extends `${infer Start}:${infer Param}/${infer Rest}`
? { [K in Param]: string } & ExtractParams<Rest>
: T extends `${infer Start}:${infer Param}`
? { [K in Param]: string }
: {};
type RouteParams = ExtractParams<"/users/:userId/posts/:postId">;
// { userId: string; postId: string }infer Id captures the rest of the string after the id- prefix, and Split calls itself until the separators run out. Recursion in types has a depth limit, though, so very long strings can overwhelm the compiler.
Built-in String Manipulation Types
TypeScript has four built-in types for changing letter case: Uppercase, Lowercase, Capitalize and Uncapitalize. There is no Reverse type, for example, you would have to write one yourself:
// TypeScript provides built-in types for string manipulation
// This is how they are declared in lib.es5.d.ts (do not redeclare them, or you get Duplicate identifier):
// type Uppercase<T extends string> = intrinsic;
// type Lowercase<T extends string> = intrinsic;
// type Capitalize<T extends string> = intrinsic;
// type Uncapitalize<T extends string> = intrinsic;
// Usage examples
type Shout = Uppercase<"hello world">; // "HELLO WORLD"
type Whisper = Lowercase<"HELLO WORLD">; // "hello world"
type Title = Capitalize<"typescript">; // "Typescript"
type CamelCase = Uncapitalize<"TypeScript">; // "typeScript"
// Practical application - generating event handlers
type DOMEventName = "click" | "focus" | "blur" | "change" | "submit";
type EventHandlerName<T extends DOMEventName> = `on${Capitalize<T>}`;
type ClickHandler = EventHandlerName<"click">; // "onClick"
type FocusHandler = EventHandlerName<"focus">; // "onFocus"
// Automatic event handler mapping
type EventHandlers = {
[E in DOMEventName as EventHandlerName<E>]: (event: Event) => void;
};
// {
// onClick: (event: Event) => void;
// onFocus: (event: Event) => void;
// onBlur: (event: Event) => void;
// onChange: (event: Event) => void;
// onSubmit: (event: Event) => void;
// }The intrinsic keyword means that the compiler provides the implementation, which is why the declarations are in a comment and you simply use them. The as clause in a mapped type renames the keys, so a list of events turns into an object with the fields onClick, onFocus and the rest.
Advanced Patterns
Property Name Transformations
APIs often return fields in snake_case, while in your code you prefer camelCase. Types can convert the names for you:
// Snake case to camel case
type SnakeToCamelCase<S extends string> = S extends `${infer T}_${infer U}`
? `${T}${Capitalize<SnakeToCamelCase<U>>}`
: S;
type CamelCased = SnakeToCamelCase<"hello_world_typescript">; // "helloWorldTypescript"
// Camel case to snake case
type CamelToSnakeCase<S extends string> = S extends `${infer C}${infer Rest}`
? C extends Lowercase<C>
? `${C}${CamelToSnakeCase<Rest>}`
: `_${Lowercase<C>}${CamelToSnakeCase<Rest>}`
: S;
type SnakeCased = CamelToSnakeCase<"helloWorldTypeScript">; // "hello_world_type_script"
// Practical application - converting API response
type SnakeToCamelCaseNested<T> = T extends object
? {
[K in keyof T as SnakeToCamelCase<K & string>]: SnakeToCamelCaseNested<T[K]>
}
: T;
interface APIResponse {
user_id: number;
first_name: string;
last_name: string;
created_at: string;
user_settings: {
email_notifications: boolean;
dark_mode: boolean;
};
}
type CamelCasedResponse = SnakeToCamelCaseNested<APIResponse>;
// {
// userId: number;
// firstName: string;
// lastName: string;
// createdAt: string;
// userSettings: {
// emailNotifications: boolean;
// darkMode: boolean;
// };
// }CamelToSnakeCase checks the string character by character and turns every uppercase letter into an underscore followed by a lowercase letter. These are only types: you transform the data at runtime with a separate function, and the type merely describes the result.
Validation and Constraints
Types can also check the format of strings. Here is validation of an email address, a phone number and a hexadecimal color:
// Email format validation
type ValidateEmail<T extends string> = T extends `${infer Local}@${infer Domain}`
? Domain extends `${infer Name}.${infer Extension}`
? Extension extends "com" | "org" | "net" | "pl" | "edu"
? T
: never
: never
: never;
type ValidEmail = ValidateEmail<"user@example.com">; // "user@example.com"
type InvalidEmail = ValidateEmail<"invalid-email">; // never
// Phone number validation
type ValidatePhoneNumber<T extends string> =
T extends `+${infer CountryCode}-${infer Rest}`
? CountryCode extends `${number}`
? Rest extends `${number}-${number}-${number}`
? T
: never
: never
: never;
type ValidPhone = ValidatePhoneNumber<"+48-123-456-789">; // "+48-123-456-789"
type InvalidPhone = ValidatePhoneNumber<"123-456-789">; // never
// Hex color validation
type HexDigit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "A" | "B" | "C" | "D" | "E" | "F" | "a" | "b" | "c" | "d" | "e" | "f";
type HexColor<T extends string> = T extends `#${HexDigit}${HexDigit}${HexDigit}${infer Rest}`
? Rest extends `${HexDigit}${HexDigit}${HexDigit}`
? T
: Rest extends ""
? T
: never
: never;
type ValidHex1 = HexColor<"#FF5733">; // "#FF5733"
type ValidHex2 = HexColor<"#F53">; // "#F53"
type InvalidHex = HexColor<"#GG5733">; // neverAn invalid string gives never, so a function that accepts such a type rejects it. This works for literals known at compile time, while text typed in by a user still has to be checked at runtime.
Dynamic Type Generation
A route map described by a type gives the router control over parameters, and unions of tables and columns generate valid SQL queries:
// Routing system with type safety
type RouteDefinition = {
"/": {};
"/users": {};
"/users/:id": { id: string };
"/users/:id/posts": { id: string };
"/posts/:postId/comments/:commentId": { postId: string; commentId: string };
};
type ExtractRouteParams<T extends string> =
T extends keyof RouteDefinition
? RouteDefinition[T]
: T extends `${infer Start}/:${infer Param}/${infer Rest}`
? { [K in Param]: string } & ExtractRouteParams<`${Start}/${Rest}`>
: T extends `${infer Start}/:${infer Param}`
? { [K in Param]: string }
: {};
// Router with type safety
class TypedRouter<Routes extends Record<string, any>> {
navigate<T extends keyof Routes & string>(
path: T,
params: Routes[T]
): void {
console.log(`Navigating to ${path} with params:`, params);
}
}
const router = new TypedRouter<RouteDefinition>();
router.navigate("/", {}); // OK
router.navigate("/users/:id", { id: "123" }); // OK
router.navigate("/posts/:postId/comments/:commentId", { // OK
postId: "456",
commentId: "789"
});
// router.navigate("/users/:id", {}); // Error! Missing id
// router.navigate("/users/:id", { id: "123", extra: "field" }); // Error! Extra field
// Generating SQL queries
type Table = "users" | "posts" | "comments";
type Column<T extends Table> =
T extends "users" ? "id" | "name" | "email" | "created_at" :
T extends "posts" ? "id" | "title" | "content" | "author_id" :
T extends "comments" ? "id" | "text" | "post_id" | "user_id" :
never;
type SelectQuery<T extends Table> = `SELECT ${Column<T> | "*"} FROM ${T}`;
type WhereClause<T extends Table> = `WHERE ${Column<T>} = ?`;
type FullQuery<T extends Table> = `${SelectQuery<T>} ${WhereClause<T>}`;
type UserQuery = SelectQuery<"users">;
// "SELECT id FROM users" | "SELECT name FROM users" | ... | "SELECT * FROM users"
type PostQueryWithWhere = FullQuery<"posts">;
// "SELECT id FROM posts WHERE id = ?" | "SELECT title FROM posts WHERE title = ?" |navigate requires exactly the parameters the route describes, so a missing or an extra field is a compilation error. Watch the size of your unions: the product of several large unions grows explosively, and TypeScript refuses to work with unions of more than 100,000 members.
Practical Applications
CSS-in-JS with Type Safety
A design token system is a classic use case: the names come from combining a color and a shade, so a typo does not get through:
// Design token system
type Color = "primary" | "secondary" | "success" | "danger" | "warning";
type Shade = 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900;
type ColorToken = `color-${Color}-${Shade}`;
type Spacing = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 8 | 10 | 12 | 16 | 20 | 24 | 32;
type SpacingToken = `spacing-${Spacing}`;
type DesignToken = ColorToken | SpacingToken;
// Helper function with type safety
function token(tokenName: DesignToken): string {
return `var(--${tokenName})`;
}
const primaryColor = token("color-primary-500"); // OK
const spacing = token("spacing-4"); // OK
// const invalid = token("color-invalid-999"); // Error!
// Responsive props system
type Breakpoint = "sm" | "md" | "lg" | "xl";
type ResponsiveValue<T> = T | { [K in Breakpoint]?: T };
type FlexDirection = "row" | "column" | "row-reverse" | "column-reverse";
type JustifyContent = "start" | "end" | "center" | "between" | "around" | "evenly";
interface FlexProps {
direction?: ResponsiveValue<FlexDirection>;
justify?: ResponsiveValue<JustifyContent>;
gap?: ResponsiveValue<Spacing>;
}
// Generating CSS classes
function generateClasses<T extends string>(
prefix: string,
value: ResponsiveValue<T>
): string[] {
if (typeof value === "object") {
return Object.entries(value).map(([breakpoint, val]) =>
`${prefix}-${val}@${breakpoint}`
);
}
return [`${prefix}-${value}`];
}Five colors and nine shades give 45 names that you do not write out by hand.
API Client with Type Safety
Keys in the form "METHOD /path" describe the endpoints, and the client derives the response and request body types from them:
// API endpoint definitions
type APIEndpoints = {
"GET /users": { response: User[]; params: {} };
"GET /users/:id": { response: User; params: { id: string } };
"POST /users": { response: User; params: {}; body: CreateUserDto };
"PUT /users/:id": { response: User; params: { id: string }; body: UpdateUserDto };
"DELETE /users/:id": { response: void; params: { id: string } };
};
// Extracting method and path
type ExtractMethod<T> = T extends `${infer Method} ${infer Path}` ? Method : never;
type ExtractPath<T> = T extends `${infer Method} ${infer Path}` ? Path : never;
// Type-safe API client
class APIClient {
async request<T extends keyof APIEndpoints>(
endpoint: T,
options: {
params?: APIEndpoints[T]["params"];
body?: "body" extends keyof APIEndpoints[T] ? APIEndpoints[T]["body"] : never;
} = {}
): Promise<APIEndpoints[T]["response"]> {
const method = endpoint.split(" ")[0];
const path = endpoint.split(" ")[1];
// Replace parameters in path
let url = path;
if (options.params) {
Object.entries(options.params).forEach(([key, value]) => {
url = url.replace(`:${key}`, value as string);
});
}
console.log(`${method} ${url}`, options.body);
// API call simulation
return {} as APIEndpoints[T]["response"];
}
}
// Usage
const api = new APIClient();
api.request("GET /users"); // OK
api.request("GET /users/:id", { params: { id: "123" } }); // OK
api.request("POST /users", { body: { /* ... */ } }); // OK
// api.request("GET /users/:id"); // Compiles! params is optional
// api.request("GET /users", { body: {} }); // Error! GET has no bodyCalling GET /users with a body is an error, because body then has the type never. The parameters are optional, however, so GET /users/:id without params compiles, and enforcing them would require overloads or a conditional type for the whole options object.
Internationalization with Type Safety
Finally, translation keys: a nested object becomes a union of paths in the style of user.profile.title:
// Translation system with nested keys
type TranslationKeys = {
common: {
yes: string;
no: string;
cancel: string;
};
user: {
profile: {
title: string;
edit: string;
};
settings: {
title: string;
notifications: {
email: string;
push: string;
};
};
};
};
// Generating paths to keys
type PathsToStringProps<T> = T extends string
? []
: {
[K in keyof T]: [K, ...PathsToStringProps<T[K]>];
}[keyof T];
type TranslationPath = PathsToStringProps<TranslationKeys>;
// ["common", "yes"] | ["common", "no"] | ["user", "profile", "title"] |
// Converting array to dot-separated string
type JoinPath<T extends string[]> = T extends []
? ""
: T extends [infer First]
? First
: T extends [infer First, ...infer Rest]
? First extends string
? Rest extends string[]
? `${First}.${JoinPath<Rest> & string}`
: never
: never
: never;
type TranslationKey = JoinPath<TranslationPath>;
// "common.yes" | "common.no" | "user.profile.title" |
// Translation function with type safety
function t(key: TranslationKey): string {
// Translation retrieval implementation
return key;
}
const title = t("user.profile.title"); // OK
const email = t("user.settings.notifications.email"); // OK
// const invalid = t("user.invalid.key"); // Error!
// Translations with parameters
type TranslationWithParams = {
"welcome": { name: string };
"items_count": { count: number };
"date_format": { date: Date };
};
function tWithParams<K extends keyof TranslationWithParams>(
key: K,
params: TranslationWithParams[K]
): string {
// Implementation with parameter substitution
return `${key} with ${JSON.stringify(params)}`;
}
tWithParams("welcome", { name: "Jan" }); // OK
tWithParams("items_count", { count: 5 }); // OK
// tWithParams("welcome", { count: 5 }); // Error! Invalid parametersJoinPath<Rest> & string assures the compiler that the result of the recursion is a string; without it, inserting the result into the template causes a type error.
Template literal types are a powerful tool that brings string manipulation to the level of the type system. This lets you build more expressive and safer APIs, especially for routing, internationalization and styling systems. My advice: use them where the format of a string is a contract, for example in event and token names, not for validating user data. In the editor below you will experiment with the examples, and in the next lesson you will use this knowledge in a typed event system.
Remember: a template literal type is a label template on a test tube that will not let a sample described in the wrong format into the lab.
Code for this lesson: index.ts
// Template literal types examples in TypeScript
// 1. Basic template literal types
type Greeting = `Hello ${string}`;
type ErrorMessage = `Error: ${string}`;
const greeting: Greeting = "Hello TypeScript!"; // OK
const error: ErrorMessage = "Error: File not found"; // OK
// const invalid: Greeting = "Hi there!"; // Error!
// 2. CSS values with type safety
type CSSUnit = "px" | "%" | "em" | "rem" | "vh" | "vw";
type CSSValue = `${number}${CSSUnit}`;
const width: CSSValue = "100px";
const height: CSSValue = "50vh";
const margin: CSSValue = "2.5rem";
// 3. Event handlers - automatic name generation
type EventName = "click" | "focus" | "blur" | "change";
type EventHandlerName<T extends EventName> = `on${Capitalize<T>}`;
type ClickHandler = EventHandlerName<"click">; // "onClick"
type FocusHandler = EventHandlerName<"focus">; // "onFocus"
// Mapping event handlers
type EventHandlers = {
[E in EventName as EventHandlerName<E>]: (event: Event) => void;
};
// 4. Snake case to camel case
type SnakeToCamelCase<S extends string> = S extends `${infer T}_${infer U}`
? `${T}${Capitalize<SnakeToCamelCase<U>>}`
: S;
// Converting object properties
type SnakeToCamelCaseNested<T> = T extends object
? {
[K in keyof T as SnakeToCamelCase<K & string>]: SnakeToCamelCaseNested<T[K]>
}
: T;
// API response transformation
interface APIUserResponse {
user_id: number;
first_name: string;
last_name: string;
email_address: string;
created_at: string;
}
type CamelCasedUser = SnakeToCamelCaseNested<APIUserResponse>;
// Result: { userId, firstName, lastName, emailAddress, createdAt }
// 5. Routing with type safety
type Route<T extends string> = T extends `/users/${infer UserId}/posts/${infer PostId}`
? { userId: UserId; postId: PostId }
: T extends `/users/${infer UserId}`
? { userId: UserId }
: T extends `/posts/${infer PostId}`
? { postId: PostId }
: never;
// Testing the routing
type UserPostRoute = Route<"/users/123/posts/456">; // { userId: "123"; postId: "456" }
type UserRoute = Route<"/users/789">; // { userId: "789" }
type PostRoute = Route<"/posts/101">; // { postId: "101" }
// 6. Practical translation system
type TranslationKey =
| "common.yes"
| "common.no"
| "common.cancel"
| "user.profile.title"
| "user.profile.edit"
| "errors.notFound"
| "errors.unauthorized";
// Translation function with type safety
function t(key: TranslationKey): string {
const translations: Record<TranslationKey, string> = {
"common.yes": "Yes",
"common.no": "No",
"common.cancel": "Cancel",
"user.profile.title": "User profile",
"user.profile.edit": "Edit profile",
"errors.notFound": "Not found",
"errors.unauthorized": "Unauthorized"
};
return translations[key];
}
// Usage with full type safety
console.log(t("common.yes")); // "Yes"
console.log(t("user.profile.title")); // "User profile"
// console.log(t("invalid.key")); // Compilation error!
// 7. CSS-in-JS design tokens
type Color = "primary" | "secondary" | "success" | "danger";
type Shade = 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900;
type ColorToken = `color-${Color}-${Shade}`;
type Spacing = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 8 | 10 | 12;
type SpacingToken = `spacing-${Spacing}`;
type DesignToken = ColorToken | SpacingToken;
function token(name: DesignToken): string {
return `var(--${name})`;
}
// Using design tokens
const primaryColor = token("color-primary-500");
const dangerColor = token("color-danger-700");
const smallSpace = token("spacing-2");
const largeSpace = token("spacing-8");
console.log("Design tokens:", {
primaryColor,
dangerColor,
smallSpace,
largeSpace
});
// 8. Format validation
type Email<T extends string> = T extends `${string}@${string}.${string}` ? T : never;
type ValidEmail = Email<"user@example.com">; // "user@example.com"
type InvalidEmail = Email<"not-an-email">; // never
// Function with email validation
function sendEmail<T extends string>(email: Email<T>, subject: string): void {
console.log(`Sending email to ${email} with subject: ${subject}`);
}
sendEmail("user@example.com" as Email<"user@example.com">, "Hello!");
// sendEmail("invalid", "Test"); // Compilation error!Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What does the type declaration type Greeting =
Hello ${string}create in TypeScript?2. Which of the following is NOT a built-in string manipulation type in TypeScript?
Hands-on tasks in the game
- Code editor
Create types based on template literal types.
- Click in order
Arrange the elements of a template literal type:
- Vertical ordering
Arrange the stages of creating a template literal type:
- Horizontal ordering
Arrange the elements of a template literal type in the correct order:
- Code editor
Create a type for parsing URL paths.