Sub topic 10
Template Literal Types
Prerequisites and purpose
This chapter assumes that you know basic TypeScript types, unions, functions, object literals, and JavaScript template strings. A JavaScript template string creates text at runtime, such as ` Hello, ${name} `. A template literal type uses a similar syntax to build a set of allowed string types at compile time.
Template literal types are useful when valid strings follow a predictable pattern. They can prevent spelling mistakes in event names, CSS-like values, API paths, and other structured strings.
Building string types from unions
Start with one or more string literal unions. A union is a type that allows one value from a fixed set. TypeScript combines every member of the unions inside the template.
type Verb = "get" | "post";
type Resource = "users" | "orders";
type Route = `/${Resource}`;
type RequestName = `${Verb} ${Route}`;
const route: Route = "/users";
const request: RequestName = "get /orders";
console.log(route);
console.log(request);Route becomes " /users" or "/orders" without the extra space shown in the explanation. Its actual type is:
type Route = "/users" | "/orders";RequestName becomes these four strings:
"get /users""get /orders""post /users""post /orders"
If you assign another string, the compiler reports an error.
const invalid: RequestName = "delete /users";
// Error: Type '"delete /users"' is not assignable to type 'RequestName'.The compiler calculates these combinations during type checking. The type does not create or validate a string at runtime. If a value comes from a user, a file, or an HTTP request, you still need runtime validation.
Transforming parts of a name
TypeScript provides intrinsic string utilities for common transformations:
Uppercase<T>converts letters to uppercase.Lowercase<T>converts letters to lowercase.Capitalize<T>uppercases the first character.Uncapitalize<T>lowercases the first character.
You can combine them with a template literal type.
type EventName = "click" | "focus" | "submit";
type HandlerName = `on${Capitalize<EventName>}`;
// "onClick" | "onFocus" | "onSubmit"
type Handler = (event: Event) => void;
const handlers: Record<HandlerName, Handler> = {
onClick: () => console.log("clicked"),
onFocus: () => console.log("focused"),
onSubmit: () => console.log("submitted"),
};Record<K, V> creates an object type with keys K and values V. In this example, the object must contain all three handler names. A misspelled key or a missing key is reported by the compiler.
Using templates with object keys
Template literal types work well with mapped types. A mapped type creates properties by iterating over a union.
type Field = "name" | "email";
type ChangeHandlers = {
[K in Field as `on${Capitalize<K>}Change`]: (value: string) => void;
};
const changeHandlers: ChangeHandlers = {
onNameChange: (value) => console.log(value),
onEmailChange: (value) => console.log(value),
};The as clause remaps each key. The resulting type has onNameChange and onEmailChange properties.
How the pieces connect
Template literal types also connect naturally to discriminated unions. For example, an application can define event names from a fixed set of resources and actions, then use those names as keys for handlers. This keeps related names synchronized when you add or remove a resource.
Avoid making a template literal type unnecessarily broad. A type such as ` ${string}-${string} ` accepts almost any two-part string with a hyphen. It communicates a shape, but it cannot guarantee that either part is meaningful.
Exercise
Exercise
Define a type named ApiEvent that allows "userCreated" and "orderCreated" by combining the resource union "user" | "order" with the suffix "Created".
Show answer
Use type Resource = "user" | "order"; and type ApiEvent = ${Resource}Created;. The resulting type is "userCreated" | "orderCreated".