as const for Enum-Like Patterns
You'll learn how to use as const objects to create lightweight, type-safe alternatives to enums with string literal unions.
The Lightweight Enum Alternative
TypeScript has a built-in enum feature (which you haven't learned yet), but many developers prefer a simpler pattern: defining a plain object with as const, then extracting a union type from its values. This gives you autocomplete, type safety, and named constants without needing enum syntax.
Think of it like a menu board at a coffee shop. Instead of listing drink sizes everywhere as "small", "medium", "large", you create one reference board and point to it. The as const makes sure those values never change, and TypeScript lets you create a type representing all valid options.
Creating an Enum-Like Pattern
Here's the basic structure:
const DrinkSize = {
SMALL: "small",
MEDIUM: "medium",
LARGE: "large"
} as const;
// Extract a union type from the values
type DrinkSizeType = typeof DrinkSize[keyof typeof DrinkSize];
// Result: "small" | "medium" | "large"
function orderDrink(size: DrinkSizeType) {
console.log(`Ordered ${size} drink`);
}
orderDrink(DrinkSize.SMALL); // ✓ Works
orderDrink("small"); // ✓ Also works (it's the literal type)
orderDrink("tiny"); // ✗ Error: not in union
The as const prevents widening to string, and typeof DrinkSize[keyof typeof DrinkSize] creates a union of all property values.
Key Takeaway: as const objects provide a simple, type-safe alternative to enums—you get named constants, autocomplete, and a string literal union type extracted from the values, all without special syntax.