Sub topic 2
Your first template literal type
A template literal type builds a string type from smaller pieces. It uses the same backtick and ${} syntax as a runtime template string, but it describes a set of strings the compiler will accept. This chapter covers the syntax, how the compiler decides whether a string matches, and the edge cases you will hit first.
What this chapter assumes
You should already be comfortable with these topics:
- Type aliases and string literal types such as
"red". - Union types such as
"red" | "blue". - Generic type parameters with
extendsconstraints.
Template literal types need TypeScript 4.1 or later. The runtime template string behavior shown below needs 4.3 or later.
The basic syntax
Write a string literal type in backticks. Put a type inside ${} wherever the string may vary.
type Greeting = `Hello, ${string}`;
const ok: Greeting = "Hello, world";
// const bad: Greeting = "Hi, world"; // Error: not assignable to type `Hello, ${string}`Greeting is the set of all strings that start with Hello, followed by any text. The literal parts (Hello, ) must match exactly. The placeholder (${string}) matches any string.
The type is a pattern, not a single value. It is more specific than string and looser than one literal like "Hello, world".
Where the check happens
The compiler checks a candidate string against the pattern from left to right.
Three consequences follow from this check:
- Matching is case sensitive.
"hello, world"is rejected. - The placeholder can match an empty string.
"Hello, "is assignable toGreeting. - The check happens at compile time only. Nothing about the type exists at runtime.
Patterns can have several parts
A placeholder can sit at the start, in the middle, or at the end. You can use more than one.
type ApiPath = `/api/${string}`;
type Suffix = `${string}.json`;
type Pair = `${string}-${string}`;
const a: ApiPath = "/api/users";
const b: Suffix = "config.json";
const c: Pair = "left-right";
const d: Pair = "a-b-c"; // also valid: the first or later hyphen can split the stringWith Pair, the string "a-b-c" matches because the compiler can split it so that each placeholder takes a part. For a pattern with several adjacent placeholders and literals, the compiler finds some split that works. Later chapters show how infer makes this splitting visible.
Template literal types are subtypes of string
Every template literal type is assignable to string. The reverse is not true.
type Greeting = `Hello, ${string}`;
declare const greeting: Greeting;
const asString: string = greeting; // OK
declare const anyText: string;
// const asGreeting: Greeting = anyText; // Error: string is not assignable to GreetingThis matters in real code. A plain string variable does not satisfy a template literal parameter, even if its runtime value would match.
Using a pattern as a parameter type
A pattern type is useful when a function accepts strings that follow a convention.
type ApiPath = `/api/${string}`;
function isApiPath(value: string): value is ApiPath {
return value.startsWith("/api/");
}
function buildUrl(path: ApiPath): string {
return `https://example.com${path}`;
}
const fixed = "/api/users";
console.log(buildUrl(fixed)); // OK: const keeps the literal type "/api/users"
let widened = "/api/orders";
// buildUrl(widened); // Error: widened has type string
if (isApiPath(widened)) {
console.log(buildUrl(widened)); // OK: the type guard narrows string to ApiPath
}The const declaration keeps the literal type, so the call passes. The let declaration widens to string, so the call fails until a type guard narrows it. The guard's body is ordinary runtime code, so the compiler trusts your check. If the guard is wrong, the types will be wrong too.
Template strings at runtime versus template literal types
The same backtick syntax appears in two places, and they behave differently.
- A template literal type is in type position. It describes a set of strings.
- A template string expression is in value position. It produces a string.
By default, a template string expression has type string, even if every part is a literal.
const name = "Ada";
const plain = `Hello, ${name}`; // type: string
const exact = `Hello, ${name}` as const; // type: "Hello, Ada"When the expression has a template literal type as its expected type, the compiler gives it a template literal type too. This lets you build a value and return it without a cast.
type Greeting = `Hello, ${string}`;
function greet(name: string): Greeting {
return `Hello, ${name}`; // OK: contextually typed as Greeting
}
console.log(greet("Grace"));Without the return type annotation, greet would return string. Annotating the return type is what makes the compiler check the expression against the pattern. If you wrote ` return Hi, ${name} ` instead, you would get an error.
Generic template literal types
A template literal type can take type parameters. The parameter in a placeholder usually needs a constraint that allows string-like types.
type Prefixed<T extends string> = `app-${T}`;
type Main = Prefixed<"main">; // "app-main"
type AnyApp = Prefixed<string>; // `app-${string}`Passing a literal produces one exact string type. Passing string produces a pattern, so the result stays as wide as the input. Passing a union is covered in the next chapter, where unions expand into every combination.
What can go inside a placeholder
Placeholders accept string, number, bigint, boolean, null and undefined, plus literal types and unions of these. An object type or a function type is an error.
type Mixed = `${"a"}-${42}-${true}`; // "a-42-true"
type Missing = `v${null}`; // "vnull"Literal types inside placeholders are resolved immediately. The compiler turns the whole template into one plain string literal type.
| Placeholder type | Contribution to the result |
|---|---|
| `"a"` | the text `a` |
| `42` | the text `42` |
| `10n` | the text `10` |
| `true` | the text `true` |
| `null` | the text `null` |
| `undefined` | the text `undefined` |
| `string` | any string, so the result becomes a pattern |
| `number` | any numeric string, so the result becomes a pattern |
The string and number rows are the ones that turn an exact type into a pattern. The chapter on placeholders covers them in detail.
Common errors
Expecting a `string` variable to match
The most common mistake is passing a general string to a pattern parameter. The compiler cannot know the contents. Fix it with a const declaration, an as const assertion, or a type guard like isApiPath above.
Forgetting the literal part is exact
` Hello, ${string} requires the comma and the space. "Hello,world"` is rejected. When a pattern fails to match, check the literal text character by character, including spaces and case.
Believing the type validates at runtime
Types are erased when TypeScript compiles to JavaScript. A function typed to accept ApiPath still receives whatever the caller sends if the call comes from untyped code, JSON, or user input. Validate untrusted input at the boundary with a runtime check, then narrow with a type guard.
Assigning a wider pattern to a narrower one
A pattern is only assignable to another pattern if every string it describes is also allowed by the target. string is not assignable to ` /api/${string} `, and a loose pattern is not assignable to a stricter one.
Putting it together
This example combines a pattern type, a generic helper, and a type guard in one small module.
type Version = `v${number}.${number}`;
type ReleaseTag<T extends string> = `release-${T}`;
function isVersion(value: string): value is Version {
return /^v\d+(\.\d+)?\.\d+(\.\d+)?$/.test(value);
}
const stable: Version = "v1.4";
const tag: ReleaseTag<"stable"> = "release-stable";
function describe(input: string): string {
return isVersion(input) ? `version ${input}` : `not a version: ${input}`;
}
console.log(stable, tag);
console.log(describe("v2.0"));
console.log(describe("latest"));Version uses ${number} placeholders, which are explained in the placeholders chapter. For now, notice that "v1.4" is accepted, and that the runtime regex is separate from the type. The regex here is deliberately simple, and the compiler does not check that it agrees with the pattern.
Exercise
Given type Route = /users/${string}, which of these strings are assignable to Route: "/users/42", "/users/", "/user/42", "/Users/42"? Then explain why a variable declared with let x = "/users/42" cannot be passed to a function that takes Route, and name two ways to make the call compile.
Show answer
"/users/42" and "/users/" are assignable. The string placeholder can match an empty string, so "/users/" passes. "/user/42" fails because the literal prefix is /users/ and the string has /user/. "/Users/42" fails because matching is case sensitive. The variable declared with let is widened to type string, and string is not assignable to a template literal type. To fix it, declare the variable with const so it keeps the literal type "/users/42", or narrow it with a type guard such as (v: string): v is Route that checks v.startsWith("/users/"). Using as const on the initializer also works.
Exercise
Write a type alias Id<T extends string> that produces strings starting with "id_" followed by T. What is Id<"user">, and what does Id<string> mean?
Show answer
type Id<T extends string> = id_${T}; Id<"user"> is the exact string type "iduser". Id<string> is the pattern `id${string}`, which accepts any string starting with "id", including "id" alone.