Sub topic 1
Starting point: string literal types and unions
Before building string patterns, start with the types that describe exact strings. A string literal type is a type whose value must be one specific string. For example, "draft" is narrower than string.
type Status = "draft";
const current: Status = "draft";
// const invalid: Status = "published"; // ErrorThe variable current can contain only the exact value "draft". TypeScript checks this restriction before the program runs.
Prerequisites
This chapter assumes you know basic TypeScript type aliases, string literal types, union types, generic type parameters, and mapped types. You should also know that a type describes which values are allowed, while a variable stores an actual value.
Combining alternatives with unions
A union type lists several possible types with the vertical bar (|). A union of string literals describes a fixed set of allowed strings.
type Status = "draft" | "published" | "archived";
function showStatus(status: Status): string {
return `The status is ${status}.`;
}
console.log(showStatus("draft"));
console.log(showStatus("published"));
// showStatus("deleted"); // ErrorThe Status type allows exactly three values. It does not allow any other string.
Unions are useful for names that come from a known vocabulary:
- Button sizes such as
"small" | "medium" | "large" - Log levels such as
"debug" | "info" | "error" - Directions such as
"up" | "down" | "left" | "right"
A union can also contain other kinds of literal values, such as numbers or booleans. This chapter focuses on strings because string unions provide the building blocks for template literal types.
Literal types and widening
TypeScript sometimes widens a literal value to a broader type. A const variable usually keeps its exact literal type because its value cannot be reassigned. A let variable usually widens to string because its value may change.
const fixed = "draft";
// fixed has the type "draft"
let changing = "draft";
// changing has the type string
changing = "published";The value of fixed is "draft", so it can be used where only "draft" is accepted. The type of changing is string, so TypeScript does not treat it as one particular status.
You can preserve literal information with an explicit annotation or with as const.
const firstStatus: Status = "draft";
const settings = {
status: "draft",
retryCount: 3,
} as const;
// settings.status has type "draft"
// settings.retryCount has type 3as const tells TypeScript to keep literal values and make object properties readonly. Use it when the exact values matter. Do not add it automatically to every object, because readonly properties can make later updates impossible.
How unions guide control flow
When a function receives a string union, TypeScript knows which cases are possible. A switch statement can handle each member explicitly.
type Access = "reader" | "editor" | "owner";
function canDelete(access: Access): boolean {
switch (access) {
case "reader":
return false;
case "editor":
return false;
case "owner":
return true;
}
}
console.log(canDelete("owner"));A union is more useful than plain string when the program has rules for particular values. With string, a function must assume that any spelling is possible. With "reader" | "editor" | "owner", misspellings become compile-time errors.
| Type | Allowed values | Example | Column |
|---|---|---|---|
| `string` | Any string | `"anything"` | |
| `"draft"` | One exact string | `"draft"` | |
| `"draft" \ | "published"` | Either listed string | `"published"` |
Why this matters for template literal types
A template literal type combines parts of other types into new string types. If those parts are string literal unions, TypeScript can calculate the valid results.
type Color = "red" | "blue";
type Size = "sm" | "lg";
type ClassName = `${Color}-${Size}`;
const buttonClass: ClassName = "red-sm";
// const invalidClass: ClassName = "green-lg"; // ErrorClassName represents the combinations "red-sm", "red-lg", "blue-sm", and "blue-lg". The next step is to understand how TypeScript creates every combination.
Exercise
What values are allowed by the type type Mode = "light" | "dark"?
Show answer
Only the exact strings "light" and "dark". Other strings, such as "LIGHT" or "auto", are not assignable to Mode.