TypeScript Enums
TypeScript Enums: Named Constants vs. Union Alternatives
A TypeScript enum defines a named set of constant values, such as order statuses or user roles. Unlike interfaces or type aliases, standard enum declarations emit real JavaScript objects at runtime.
Understanding both string enums and lighter as const union alternatives helps you pick the cleanest pattern for modern TypeScript codebases.
Numeric vs. String Enums
Numeric enums auto-increment from 0 unless initialized, while string enums assign explicit readable strings that show up cleanly in logs and JSON payloads.
enum OrderStatus {
Pending = "PENDING",
Paid = "PAID",
Shipped = "SHIPPED",
}
function canCancel(status: OrderStatus): boolean {
return status === OrderStatus.Pending;
}
console.log(OrderStatus.Paid, canCancel(OrderStatus.Pending));
Modern Alternative: as const Object + Union Type
Many TypeScript teams prefer a plain as const object over enum because it works cleanly with Node's type-stripping mode and avoids extra enum runtime helpers:
const Roles = {
Admin: "admin",
Editor: "editor",
Viewer: "viewer",
} as const;
type Role = (typeof Roles)[keyof typeof Roles]; // "admin" | "editor" | "viewer"
Common Mistakes to Avoid
- Using numeric enums with unvalidated numbers: Before TypeScript 5, passing arbitrary numbers like
99into a numeric enum parameter compiled without warning; string enums are strictly safer. - Using
const enumin published npm libraries:const enuminlines values at compile time and breaks--isolatedModulestools like Babel, Vite, andtsx. - Comparing raw string
"PAID"toOrderStatus.Paid: Even when values match, TypeScript requires usingOrderStatus.Paidbecause enums are nominally typed.
Frequently Asked Questions
What is reverse mapping in numeric enums?
TypeScript generates Status[0] === "Pending" for numeric enums, doubling object keys. String enums do not generate reverse mappings.
Which is better in modern Next.js or Vite projects: enum or union types?
String literal unions ("pending" | "paid" | "shipped") or as const objects are smaller, work with --isolatedModules and Node type stripping, and pass plain strings cleanly across APIs.
Can an enum mix string and numeric members?
Yes (called heterogeneous enums), though mixing types makes code confusing and is rarely recommended.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.