Value Unions
What
Value unions are the combination of literal types and union types. They allow you to define a type that can be one of several specific values.
How
By unioning multiple literal types together, you can create a constrained set of valid options. You can also use a type alias to make the union reusable:
type Direction = "north" | "south" | "east" | "west";
function move(direction: Direction) {
// direction must be one of the four literal strings
}
Why
This pattern is often a more ergonomic and lightweight alternative to enums. It provides excellent IDE autocompletion and ensures that a variable is restricted to a specific, meaningful set of constants.
Summary
Value unions are a staple of TypeScript development, used to define restricted sets of strings, numbers, or even booleans.