String-Literal Unions as Enum Alternatives
What you'll learn: How union types of string literals can replace enums with simpler syntax and fewer runtime artifacts.
The Lightweight Alternative
Instead of using enums, you can achieve the same type safety and autocomplete benefits by creating a union of string literal types. This approach gives you compile-time checking without generating any runtime JavaScript code.
// Instead of an enum:
enum Direction {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT"
}
// Use a string-literal union:
type Direction = "UP" | "DOWN" | "LEFT" | "RIGHT";
Why This Works Better
When you use a string-literal union, TypeScript treats it as a type-only construct. It completely disappears during compilation—there's no JavaScript object created, no extra bytes in your bundle, and no namespace pollution.
type Status = "pending" | "approved" | "rejected";
function updateStatus(status: Status): void {
// Full autocomplete for "pending" | "approved" | "rejected"
console.log(`Status: ${status}`);
}
updateStatus("approved"); // ✓ Valid
updateStatus("cancelled"); // ✗ Error: not in union
The Trade-off
The main limitation is that you're working with plain strings. There's no centralized object to iterate over, and you need to manually ensure consistency if the same values appear in multiple places. However, for most use cases, the zero-runtime-cost benefit outweighs this minor inconvenience.
Key Takeaway: String-literal unions provide enum-like type safety and autocomplete without generating runtime code, making them a leaner, more modern alternative to traditional enums.