Lesson

TypeScript Enums

10 min reading
Free Course

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 99 into a numeric enum parameter compiled without warning; string enums are strictly safer.
  • Using const enum in published npm libraries: const enum inlines values at compile time and breaks --isolatedModules tools like Babel, Vite, and tsx.
  • Comparing raw string "PAID" to OrderStatus.Paid: Even when values match, TypeScript requires using OrderStatus.Paid because 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.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
TypeScript Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum