Sub topic 2
Your First Template Literal Type
This chapter assumes you know basic TypeScript type aliases, string literal types, union types, and generic type parameters. You should also recognize a mapped type such as { [K in keyof T]: ... }.
A string literal type allows one exact string value:
type Direction = "north" | "south";
const first: Direction = "north";
// const second: Direction = "east"; // ErrorThe type Direction describes two permitted strings. This is useful when an API accepts a fixed set of names. However, many APIs accept strings that follow a pattern. For example, an event name might begin with on, or a CSS value might end with px.
A template literal type describes strings by combining fixed text with other types. It uses the same ${...} shape as a JavaScript template string, but it appears inside a type position.
Building a string pattern
The simplest template literal type contains fixed text:
type Greeting = `Hello`;
const message: Greeting = "Hello";
// const wrong: Greeting = "Hi"; // ErrorThis type is equivalent to the string literal type "Hello". The useful feature appears when the placeholder contains another type:
type Greeting = `Hello, ${string}`;
const welcome: Greeting = "Hello, world";
const question: Greeting = "Hello, TypeScript";
// const wrong: Greeting = "Hi, world"; // ErrorHere, Hello, is fixed, while ${string} means “any string after this prefix.” The compiler checks the complete shape when it checks an assignment.
A template literal type can contain more than one placeholder:
type FileName = `${string}.${string}`;
const documentName: FileName = "notes.md";
const imageName: FileName = "photo.png";This describes a string containing some text, a period, and more text. It does not prove that the extension is a real file extension. It only checks the pattern expressed by the type.
The following diagram shows how TypeScript combines fixed pieces and placeholders.
Using literal types in placeholders
A placeholder can contain a string literal type. This lets you construct a new type from known pieces:
type Protocol = "http" | "https";
type Host = "example.com" | "api.example.com";
type Url = `${Protocol}://${Host}`;
const page: Url = "https://example.com";
const api: Url = "http://api.example.com";
// const invalid: Url = "ftp://example.com"; // ErrorUrl represents combinations of the Protocol and Host types. TypeScript keeps the result as a specific set of allowed strings rather than widening it to an unrestricted string.
You can also combine a literal type with a primitive placeholder:
type UserPath = `/users/${number}`;
const userPath: UserPath = "/users/42";The ${number} placeholder accepts numeric text in this position. It does not turn the whole value into a number. userPath is still a string at runtime.
Choosing a template literal type
Use a template literal type when a string has a stable structure that the compiler can check. Good examples include:
- Names with a required prefix, such as
"onClick". - Resource paths, such as
"/users/42". - Namespaces separated by a delimiter, such as
"admin:read". - CSS-like values with a fixed unit, such as
"12px".
Do not use one merely because a string contains punctuation. If the structure is not important to the program, the ordinary string type is clearer.
A template literal type checks the shape of a value at compile time. It does not validate data received from a file, network request, or user input while the program runs. Runtime validation is still needed at those boundaries.
A small event-name example
Suppose an application uses event names that begin with on:
type EventName = `on${string}`;
function register(event: EventName, callback: () => void) {
console.log(`Registered ${event}`);
callback();
}
register("onClick", () => {
console.log("Clicked");
});
// register("click", () => {}); // ErrorThe function still receives an ordinary JavaScript string at runtime. The type prevents calls with a value that does not have the required prefix during development.
At this stage, the placeholder ${string} accepts any remaining text. Later, you can replace it with unions, case transformations, or extracted pieces to make the pattern more precise.
Exercise
Define a type named ApiRoute that accepts strings beginning with "/api/" and test it with "/api/users".
Show answer
Use type ApiRoute = \/api/${string}\;. The value const route: ApiRoute = "/api/users"; is valid, while a value such as "/users" is rejected.