Sub topic 5
Matching Families of Strings with String and Number Placeholders
This chapter assumes that you know basic TypeScript type aliases, string literal types, union types, generics, and mapped types. You should also know that a type is checked at compile time, while a value exists at runtime.
From exact strings to string families
A string literal type describes one exact string:
type Method = "GET" | "POST";
const readMethod: Method = "GET";
// const invalidMethod: Method = "DELETE"; // ErrorA template literal type uses the same ${...} shape as a JavaScript template string, but it creates a type instead of a runtime string. A placeholder describes the part that may vary.
type Greeting = `Hello, ${string}`;
const first: Greeting = "Hello, world";
const second: Greeting = "Hello, TypeScript";
// const invalid: Greeting = "Hi, TypeScript"; // ErrorGreeting accepts every string that starts with "Hello, ". The ${string} placeholder can contain any string, including an empty string.
The placeholder does not perform validation while the program runs. It only checks assignments and other type relationships during compilation.
Number placeholders
A number placeholder matches strings that contain a valid numeric literal in that position. This is useful for describing formatted values such as CSS lengths.
type Px = `${number}px`;
const width: Px = "12px";
const preciseWidth: Px = "1.5px";
const negativeWidth: Px = "-4px";
// const invalidWidth: Px = "wide px"; // Error
// const missingUnit: Px = "12"; // ErrorThe complete value is still a string. The placeholder only controls which text may appear before "px".
You can combine several allowed units with a union:
type Unit = "px" | "rem" | "%";
type Length = `${number}${Unit}`;
const cardWidth: Length = "320px";
const textSize: Length = "1.25rem";
const fluidWidth: Length = "80%";
// const invalidUnit: Length = "20pt"; // ErrorThe Unit union describes the suffix. Length then combines every number with every allowed suffix.
Combining placeholders with unions
When a placeholder contains a union, TypeScript produces the possible combinations. This lets you model naming conventions without writing every member manually.
type Color = "red" | "blue";
type Size = "sm" | "lg";
type ClassName = `${Color}-${Size}`;
const smallRed: ClassName = "red-sm";
const largeBlue: ClassName = "blue-lg";
// const invalidClass: ClassName = "green-sm"; // Error
// const invalidSize: ClassName = "red-md"; // ErrorConceptually, ClassName becomes this union:
type ExpandedClassName =
| "red-sm"
| "red-lg"
| "blue-sm"
| "blue-lg";The template form is easier to maintain. If you add "green" to Color, TypeScript adds the corresponding "green-sm" and "green-lg" members automatically.
This expansion is called a cross product. Each union in the template combines with the members of the other unions.
Other primitive placeholders
String and number placeholders are the most common. Other primitive types can also describe their textual forms.
type BooleanText = `${boolean}`;
type StateLabel = `state:${"open" | "closed"}`;
const enabled: BooleanText = "true";
const disabled: BooleanText = "false";
const open: StateLabel = "state:open";Use a narrow literal union when the accepted values are known. Use ${string} or ${number} when the variable part genuinely has many possible values.
A broad placeholder can make a type less useful:
type AnyText = `${string}`;
const message: AnyText = "anything";AnyText does not impose a meaningful pattern. In practice, string communicates the same idea more directly. Add fixed text around a placeholder when you want the type to reject unrelated strings.
Common errors and design choices
A frequent mistake is putting the unit outside the type:
type Incorrect = number;
type Correct = `${number}px`;Incorrect describes a JavaScript number such as 12. Correct describes the string "12px".
Another mistake is assuming that a template literal type converts or validates a runtime value:
function setWidth(value: string) {
// TypeScript cannot check arbitrary data received here.
}
setWidth("not a length");To check external data, such as JSON or user input, add runtime validation. The template literal type protects values after they have entered the typed part of your program.
Exercise
Exercise
Define a type named EventKey that accepts "user:created" and "user:deleted", but rejects "user:updated".
Show answer
type EventKey = \user:${"created" | "deleted"}\;