Sub topic 5
Matching families of strings with string and number placeholders
This chapter assumes you can write type aliases and generics, you know string literal and union types, and you have seen the basic ${} template literal type syntax from the earlier chapters. Here we look at what the placeholder positions accept, how TypeScript decides whether a string belongs to a pattern, and where patterns are too loose.
From a fixed set of strings to a family of strings
A union of literals lists every member. A placeholder describes a pattern instead, so the set of matching strings can be infinite.
type Greeting = `Hello, ${string}`;
const a: Greeting = "Hello, Ada";
const b: Greeting = "Hello, "; // the placeholder may be empty
// @ts-expect-error
const c: Greeting = "Hi, Ada";${string} matches any string, including the empty string. A type like Greeting is a subtype of string. You can pass a Greeting where a string is expected, but not the other way round.
declare const anyText: string;
// @ts-expect-error: string is not known to start with "Hello, "
const d: Greeting = anyText;Which types can go in a placeholder
A placeholder accepts only types that have a text form: string, number, bigint, boolean, null, undefined, and unions or literals of those. Objects, symbols, and functions are rejected.
| Placeholder | What it produces | Example match | Column | Column |
|---|---|---|---|---|
| `${string}` | A pattern: any text, possibly empty | `"anything"` | ||
| `${number}` | A pattern: any text that reads as a finite number | `"42"`, `"-1.5"`, `"1e3"` | ||
| `${bigint}` | A pattern: integer text | `"10"` | ||
| `${boolean}` | The union `"true" \ | "false"` | `"true"` | |
| `${null}` / `${undefined}` | The literal `"null"` / `"undefined"` | `"null"` | ||
| `${1 \ | 2}` | The union `"1" \ | "2"` | `"2"` |
The table shows two behaviors. string, number, and bigint are wide types, so they produce a pattern that stays open. boolean, null, undefined, and literal unions are finite, so they expand into a union of literal strings, as in the earlier chapter on unions.
type Id = `user-${number}`;
type Flag = `debug=${boolean}`; // "debug=true" | "debug=false"
type Missing = `value: ${null | undefined}`; // "value: null" | "value: undefined"
type Level = `level-${1 | 2 | 3}`; // "level-1" | "level-2" | "level-3"
const id: Id = "user-17";
// @ts-expect-error
const badId: Id = "user-abc";What counts as a number
${number} does not mean "digits". A string matches when JavaScript can convert it to a finite number, and it is not empty. The text does not have to be the canonical form of that number.
type Px = `${number}px`;
const a: Px = "12px";
const b: Px = "1.5px";
const c: Px = "-4px";
const d: Px = "1e3px"; // exponent notation is a valid number
const e: Px = "0x1Fpx"; // so is hex
// @ts-expect-error
const f: Px = "wide px";
// @ts-expect-error
const g: Px = "px"; // an empty number is not a number
// @ts-expect-error
const h: Px = "Infinitypx"; // not finiteSo ${number}px is looser than "a CSS length". It allows "0x1Fpx", which CSS rejects. If a value comes from outside your program, such as user input or a config file, treat the type as a compile-time hint and validate at runtime.
const pxPattern = /^-?\d+(\.\d+)?px$/;
function isPx(value: string): value is Px {
return pxPattern.test(value);
}This guard is stricter than the type. That is safe, because it only returns true for strings the type also allows. A guard that is looser than its type would be unsound.
How TypeScript matches a string against a pattern
For a literal string such as "1.2.3", TypeScript works through the pattern from left to right.
- It checks that the string starts with the first fixed text of the pattern.
- For each placeholder, it finds the next fixed text after it and takes everything before that text as the placeholder's value. The first occurrence wins.
- The last placeholder takes the rest of the string, up to the final fixed text.
- It checks that each captured piece fits its placeholder type.
type Version = `${number}.${number}.${number}`;
const v1: Version = "1.2.3";
const v2: Version = "10.0.25";
// @ts-expect-error: only one dot
const v3: Version = "1.2";
// @ts-expect-error: "x" is not a number
const v4: Version = "1.x.3";The "first occurrence wins" rule matters when the delimiter can also appear inside a value. With ${string}-${string}, the string "a-b-c" matches, with "a" in the first slot and "b-c" in the second. The pattern cannot say "exactly one hyphen".
type Pair = `${string}-${string}`;
const p1: Pair = "a-b";
const p2: Pair = "a-b-c"; // accepted: the second slot is "b-c"
// @ts-expect-error
const p3: Pair = "ab";Combining placeholders with unions
A union inside a template expands first, and each expanded member keeps its open placeholders. The result is a union of patterns.
type Unit = "px" | "em" | "%";
type Length = `${number}${Unit}`;
// `${number}px` | `${number}em` | `${number}%`
function setWidth(value: Length): void {
console.log(`width set to ${value}`);
}
setWidth("10px");
setWidth("2.5em");
setWidth("50%");
// @ts-expect-error
setWidth("50");Two wide placeholders next to each other, such as ${number}${number}, are legal but hard to reason about. There is no delimiter to split on, so the boundary between the two pieces is ambiguous. Put a fixed character between wide placeholders.
Patterns as object keys
Since TypeScript 4.4, an index signature can use a template literal pattern as its key type. This describes objects whose keys follow a naming rule.
type DataAttributes = { [key: `data-${string}`]: string };
const attrs: DataAttributes = {
"data-id": "7",
"data-role": "admin",
};
// @ts-expect-error: "id" does not match `data-${string}`
const bad: DataAttributes = { id: "7" };
const role: string = attrs["data-role"];The same works with numeric patterns. { [key: item${number}]: boolean } allows item1, item22, and item-3, but rejects itemX.
Computed strings often widen to string
A template expression at runtime does not automatically get a template literal type. TypeScript gives it one only when the context asks for it, for example through a return type or an annotation, or when you write as const.
function px(value: number): `${number}px` {
return `${value}px`; // contextually typed by the return type
}
const n = 12;
const inferred = `${n}px`; // type: string
const annotated: `${number}px` = `${n}px`; // ok
const frozen = `${n}px` as const; // type: `${number}px`The same widening applies to variables. A let declaration widens its literal to string, so it will not satisfy a template literal parameter.
let w1 = "10px";
const w2 = "10px";
setWidth(w2);
// @ts-expect-error: w1 has type string
setWidth(w1);Extracting a number type with infer
You can capture a number from a string type with infer and an extends number constraint (TypeScript 4.8 and later). The next chapters cover infer in detail. This is a preview of how number placeholders connect to it.
type ToNumber<S extends string> = S extends `${infer N extends number}` ? N : never;
type A = ToNumber<"42">; // 42
type B = ToNumber<"abc">; // neverWithout the extends number constraint, infer N captures the text "42", not the number 42.
Common mistakes
- Treating
${string}as "non-empty". It also matches""."px"is assignable to${string}px. - Treating
${number}as "digits". It accepts signs, decimals, exponents, and hex, and rejects the empty string andInfinity. - Expecting
stringto flow into a pattern. A value typedstringis never assignable to a template pattern without a guard or an assertion. - Relying on a delimiter that can appear in values.
${string}-${string}allows any number of hyphens. - Passing mutable variables.
letand non-constobject properties widen tostring.
type Email = `${string}@${string}`;
const ok: Email = "[email protected]";
const weak: Email = "@"; // accepted: both sides may be emptyThe Email type catches a missing @ and nothing more. Use it to catch typing slips, not to validate input.
Choosing between a union and a pattern
| Situation | Prefer | Reason |
|---|---|---|
| A small, known set of values | Union of literals | Exact, and editors can autocomplete it |
| An open set with a known shape, such as `data-*` keys | Pattern with `${string}` | Accepts new values without edits |
| Numeric text with a unit | Pattern with `${number}` and a union of units | Precise on the unit, open on the value |
| Pattern combined with a few known values | Union of both | Keeps autocomplete for the known values |
A pattern gives up autocomplete, because the editor cannot list infinitely many strings. If you want suggestions and also want to allow other strings, "a" | "b" | (string & {}) is a different technique from the one in this chapter. Template patterns do not provide it.
Exercise
Define a type Hex for strings that start with # followed by anything, and a type Ratio for strings of the form "3:4" where both sides are numbers. Then say which of these assignments fail: const a: Ratio = "16:9", const b: Ratio = "16/9", const c: Hex = "#".
Show answer
type Hex = #${string}; and type Ratio = ${number}:${number};. Only b fails: "16/9" has no :. Assignment a works because "16" and "9" are both numbers. Assignment c works because ${string} may be empty, so "#" matches #${string}.
Exercise
Given type Spacing = ${number}${"px" | "rem"};, decide whether each of these is assignable: "4rem", "4 rem", "rem", "-0.5px". Explain the two that are not.
Show answer
"4rem" and "-0.5px" are assignable. "4 rem" is not: the type expands to ${number}px | ${number}rem, and "4 " would have to be the number, so the string fails to match either pattern because the space precedes the unit text and +"4 " is only valid if surrounding whitespace is tolerated, which makes this a poor thing to depend on. In practice, treat it as not matching and avoid whitespace in such strings. "rem" is not assignable because the number part is empty, and an empty string is not a valid number.
Exercise
Why does const w = ${n}px` (with const n = 12) have type string, and give two ways to make it ${number}px`?
Show answer
A template expression is typed as string unless the context asks for a template literal type. Either annotate the variable, as in const w: ${number}px = ${n}px`, or add as const, as in ${n}px as const `. A function return type annotation works the same way as the annotation.