The best way to define enums in JavaScript is a frozen plain object with Object.freeze({ ... }) (or Symbol() values when unique, collision-free identities are needed), and in TypeScript is a const object paired with a derived union type (const Direction = { Up: "UP", Down: "DOWN" } as const; type Direction = (typeof Direction)[keyof typeof Direction];) rather than TypeScript’s runtime enum keyword. Frozen as const objects stay tree-shakeable, runtime-inspectable, and free of extra emitted IIFE code, while still giving full type safety, autocomplete, and exhaustive checking in TypeScript.
1. Idiomatic Enums in JavaScript (Object.freeze() and Symbol())
JavaScript has no native enum keyword; use Object.freeze() on a dictionary object for readable string/number constants, or Symbol() values when distinct internal tokens matter more than serializable strings:
// Frozen object enum for serializable string/number states
const OrderStatus = Object.freeze({
Pending: "PENDING",
Paid: "PAID",
Shipped: "SHIPPED",
Cancelled: "CANCELLED"
});
// Symbol-based enum for guaranteed unique internal event tokens
const LogLevel = Object.freeze({
Debug: Symbol("debug"),
Info: Symbol("info"),
Error: Symbol("error")
});
function transitionOrder(currentStatus) {
if (currentStatus === OrderStatus.Pending) {
return OrderStatus.Paid;
}
return currentStatus;
}
console.log(transitionOrder(OrderStatus.Pending)); // "PAID"
console.log(Object.isFrozen(OrderStatus)); // true
- Prevent accidental mutation:
Object.freeze()stops properties from being added, deleted, or overwritten at runtime (throwing in strict mode). - Serializable vs. unique tokens: String/number values work cleanly in JSON, URLs, and databases, whereas
Symbol()guarantees every member is distinct (Symbol("x") !== Symbol("x")).
2. Best Practice in TypeScript (as const Object + Union Type)
In TypeScript, prefer a const object with a derived union type over the TypeScript enum keyword so you get strict type checking without generating extra runtime helper code or numeric reverse mappings:
// Recommended TypeScript enum pattern: `as const` object + derived union type
const HttpMethod = {
Get: "GET",
Post: "POST",
Put: "PUT",
Delete: "DELETE"
} as const;
type HttpMethod = (typeof HttpMethod)[keyof typeof HttpMethod];
// Type HttpMethod is "GET" | "POST" | "PUT" | "DELETE"
function requestUrl(method: HttpMethod, endpoint: string): string {
switch (method) {
case HttpMethod.Get:
case HttpMethod.Post:
case HttpMethod.Put:
case HttpMethod.Delete:
return `${method} ${endpoint}`;
default: {
// Exhaustiveness check: fails compilation if a new HttpMethod is unhandled
const _exhaustive: never = method;
throw new Error(`Unhandled HTTP method: ${String(_exhaustive)}`);
}
}
}
console.log(requestUrl(HttpMethod.Get, "/v1/items")); // "GET /v1/items"
- Zero runtime bloat and better tree-shaking: Plain objects compile away cleanly without emitting TypeScript enum boilerplate.
- Runtime iteration and validation: Unlike type-only unions,
Object.values(HttpMethod)exists at runtime for validating untrusted input or building dropdown options.
3. Why Avoid TypeScript enum and const enum in Most Codebases
TypeScript’s built-in enum and const enum introduce subtle runtime and tooling pitfalls that as const objects avoid:
// Pitfalls of TypeScript numeric/string `enum` vs. `as const` object:
// 1. Numeric `enum` generates reverse mappings (e.g., `Role[0] === "Admin"`),
// which makes `Object.keys(Role)` contain both keys and numbers.
// 2. Numeric `enum` is NOT type-safe against arbitrary out-of-range numbers
// (e.g., `const r: NumericRole = 999` compiles without error).
// 3. `const enum` can break under `isolatedModules`, Babel/SWC transpilers,
// or published library declarations unless configured carefully.
function isValidOrderStatus(value: unknown): value is (typeof OrderStatus)[keyof typeof OrderStatus] {
return (
typeof value === "string" &&
Object.values(OrderStatus).includes(
value as (typeof OrderStatus)[keyof typeof OrderStatus]
)
);
}
console.log(isValidOrderStatus("PAID")); // true
console.log(isValidOrderStatus("INVALID")); // false
- Type guard friendly: You can validate external inputs (like API payloads or query params) against
Object.values(...)at runtime and narrow the TypeScript type cleanly. - When TS
enumstill appears: You may still use it when interoperating with existing codebases or generated types that already standardize onenum.
