String Literal Unions as Lightweight Enums
You'll learn how to create a fixed set of allowed values using string literal unions, gaining many benefits of enums without any runtime code.
The Core Idea
A string literal union combines multiple string literals with the | operator to define a type that can only be one of those exact strings. This pattern gives you enum-like behavior—a predefined set of valid values—but compiles away to nothing at runtime. It's lightweight, type-safe, and plays beautifully with JavaScript's native strings.
type Direction = "north" | "south" | "east" | "west";
function move(direction: Direction) {
console.log(`Moving ${direction}`);
}
move("north"); // ✓ Valid
move("up"); // ✗ Error: Argument of type '"up"' is not assignable
Why This Matters
Unlike numeric enums that generate runtime code, string literal unions are purely compile-time. You get autocomplete, exhaustive checking, and type safety without adding bytes to your bundle. The strings themselves are just strings—they work naturally with JSON, APIs, and databases.
type Status = "pending" | "approved" | "rejected";
const currentStatus: Status = "pending";
// TypeScript knows exactly which values are valid
Practical Use Cases
Define fixed sets of options, states, or categories:
type Theme = "light" | "dark" | "auto";
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";
type Size = "small" | "medium" | "large";
These behave like enums but remain simple strings at runtime, making them perfect for configurations, API contracts, and state machines.
Key Takeaway: String literal unions provide enum-like safety and autocomplete without runtime overhead—use them whenever you need a fixed set of string values.