Sub topic 2
Combining Literal Types into Unions
Assume you know basic TypeScript types, function annotations, object literals, and JavaScript switch statements. This chapter shows how to combine literal types into a union that represents a fixed set of allowed values.
What a literal type is
A literal type describes one exact value. For example, "up" is different from string. The type string allows any string, while the literal type "up" allows only the text "up".
The same idea works for numbers and booleans:
type StartCode = 200;
type Enabled = true;
type Direction = "up";A literal type is useful when a value has a small, known set of valid choices. A direction, status, permission, or response code often fits this model.
Building a union
A union type combines two or more types with the | operator. A union means that a value can be one member of the set.
type Direction = "up" | "down" | "left" | "right";
function move(direction: Direction): void {
console.log(`Moving ${direction}`);
}
move("up"); // OK
move("diagonal"); // ErrorThe parameter accepts exactly one of the four listed strings. It does not accept arbitrary strings.
You can combine numeric and boolean literals in the same way:
type HttpSuccess = 200 | 201 | 204;
type FeatureFlag = true | false;
const status: HttpSuccess = 201;
const enabled: FeatureFlag = false;true | false is equivalent to boolean, so a boolean literal union is mainly useful when it appears inside a larger type.
Checking a union in a function
A function can use a union to reject invalid input before the program runs.
type LogLevel = "debug" | "info" | "warn" | "error";
function formatLog(level: LogLevel, message: string): string {
return `[${level.toUpperCase()}] ${message}`;
}
console.log(formatLog("warn", "Cache is almost full"));
// [WARN] Cache is almost full
// formatLog("warning", "Cache is almost full");
// Error: "warning" is not assignable to type LogLevelThe compiler checks calls at development time. This protects the function from unsupported values and makes its valid inputs visible to people reading the code.
You can also use a union for an object property:
type User = {
name: string;
role: "reader" | "editor" | "owner";
};
const user: User = {
name: "Mina",
role: "editor",
};The role property cannot contain an arbitrary string. It must be one of the three allowed roles.
Understanding the set of values
The following table shows how broad types compare with literal unions.
| Type | Values accepted | Example | Column |
|---|---|---|---|
| `string` | Any string | `"anything"` | |
| `"open" \ | "closed"` | Only two strings | `"open"` |
| `number` | Any number | `42` | |
| `200 \ | 404` | Only two numbers | `404` |
A union can also combine literal types with a broader type, but that often reduces the benefit of the restriction:
type KnownOrCustomStatus = "active" | "inactive" | string;Because every string is already included by string, this type effectively accepts any string. Use such a type only when you intentionally want to document known common values while still allowing custom values.
Visualizing a union
Common mistakes
A frequent mistake is using a broad annotation when a literal union is intended:
function move(direction: string): void {
console.log(direction);
}This function accepts "diagonal" because string includes every string. Replace string with Direction when the valid set is known.
Another mistake is misspelling a member. "erro" and "error" are different literal types, so TypeScript catches the mismatch.
A union can describe related values, but it does not automatically explain how to process them. Later, you can narrow a union by checking its value with if statements or switch statements.
Exercise
Define a type named Theme that allows only "light" and "dark", then write a function that returns the selected theme.
Show answer
type Theme = "light" | "dark"; function chooseTheme(theme: Theme): Theme { return theme; }