TypeScript Enums
A TypeScript enum is a way to give friendly names to a set of related values. Instead of scattering magic numbers or raw strings through your code, you define them once in an enum and reuse the names. In real projects, this makes status codes, roles, and modes easier to read and safer to change.
This tutorial covers numeric enums, string enums, reverse mapping, const enums, and how to use enums inside functions. You will also see an honest comparison between enums and union of string literals, and a recommendation on when to choose each.
What Is a TypeScript Enum?
A TypeScript enum is a named collection of constant values. You define it with the enum keyword, and each member gets a name and a value. Enums solve the problem of magic values: numbers or strings that appear in many places with no explanation.
Here is a small example:
enum Direction {
North,
East,
South,
West,
}
console.log(Direction.North);
console.log(Direction.West);
// Output: 0
// Output: 3
By default, the first member gets 0 and each next member increases by one. The names make your code read clearly: Direction.North is easier to understand than 0.
How Do Numeric Enums Work?
A numeric enum stores numbers. You can let TypeScript auto-increment the values, or you can set them yourself. Auto-increment is handy for simple lists. Custom values are useful when the numbers must match an external system, like an API.
enum HttpStatus {
Ok = 200,
NotFound = 404,
ServerError = 500,
}
enum Priority {
Low,
Medium,
High,
}
console.log(HttpStatus.NotFound);
console.log(Priority.High);
// Output: 404
// Output: 2
How it works: In HttpStatus, each member has an explicit value, so no auto-increment happens. In Priority, the first member is 0, the second 1, and the third 2. You can also start auto-increment from a custom point by setting the first value, and the rest follow.
How Do String Enums Work?
A string enum stores string values. Every member must have an explicit string value because there is no auto-increment for strings. String enums are easier to read in logs and JSON because the value is meaningful.
enum OrderStatus {
Pending = "PENDING",
Shipped = "SHIPPED",
Delivered = "DELIVERED",
Cancelled = "CANCELLED",
}
console.log(OrderStatus.Shipped);
// Output: SHIPPED
How it works: Each member maps a name to a string. The value "SHIPPED" is what appears at runtime, so logs and network responses show a readable word instead of a number. This is the main reason many teams prefer string enums for statuses.
What Is Reverse Mapping in Numeric Enums?
Reverse mapping means you can look up the name of a numeric enum member by its value. Numeric enums generate both name-to-value and value-to-name entries in the compiled JavaScript. String enums do not have this feature.
enum Color {
Red,
Green,
Blue,
}
console.log(Color[1]);
// Output: Green
How it works: The compiled JavaScript object contains both { Red: 0, Green: 1, Blue: 2 } and { 0: "Red", 1: "Green", 2: "Blue" }. So Color[1] returns the string "Green". This is useful for debugging, but it also makes numeric enums slightly larger in output. String enums skip reverse mapping entirely.
What Is a const enum?
A const enum is an enum that the compiler inlines at every usage site and removes from the output. This makes the compiled JavaScript smaller and slightly faster. However, const enums do not work with isolatedModules, a compiler option used by many modern build tools.
const enum Role {
Admin = "ADMIN",
Editor = "EDITOR",
Viewer = "VIEWER",
}
const currentRole = Role.Editor;
console.log(currentRole);
// Output: EDITOR
How it works: The compiler replaces Role.Editor with "EDITOR" directly in the JavaScript output. There is no Role object at runtime. The isolatedModules caveat: when that option is on, each file is compiled separately, so the compiler cannot see the full enum definition. TypeScript then reports an error or warns you to avoid const enums. For beginners, use regular enums unless you have a clear size reason.
How Do You Use Enums in Functions?
Enums pair naturally with functions. You accept an enum member as a parameter and switch on it. TypeScript then checks that every call passes a valid member.
enum OrderStatus {
Pending = "PENDING",
Shipped = "SHIPPED",
Delivered = "DELIVERED",
Cancelled = "CANCELLED",
}
function describeOrder(status: OrderStatus): string {
switch (status) {
case OrderStatus.Pending:
return "Your order is being prepared.";
case OrderStatus.Shipped:
return "Your order is on the way.";
case OrderStatus.Delivered:
return "Your order has arrived.";
case OrderStatus.Cancelled:
return "Your order was cancelled.";
}
}
console.log(describeOrder(OrderStatus.Shipped));
// Output: Your order is on the way.
How it works: The parameter status: OrderStatus restricts the argument to a member of the enum. Each case uses the enum member, so a typo like OrderStatus.Shiped would be a compile error. The switch is exhaustive because every enum member is handled, so TypeScript knows the function always returns a string. If you miss a case, the return type becomes string | undefined under strict mode, and you must handle it.
Enum vs Union of String Literals
A union of string literals is an alternative to enums. It looks like "PENDING" | "SHIPPED" | "DELIVERED". The table below compares the two approaches honestly.
| Feature | Enum | Union of String Literals |
|---|---|---|
| Runtime object | Yes (generated JavaScript) | No, types vanish |
| Reverse mapping | Only numeric enums | Not applicable |
| Readability | Very high with named members | Good, but strings repeat |
| Bundle size | Adds a small object | Zero extra runtime code |
| Interop with JSON | Value is the string (string enum) | Value is the string |
Works with isolatedModules |
Yes (regular enum) | Yes |
| Refactoring | Easy, one place to change | Manual string updates |
The honest recommendation: for most modern projects, a union of string literals plus a const object is simpler and safer. It has no runtime overhead and works with every build tool. Enums remain a good choice when you want a single named type, when you are working in a codebase that already uses them, or when you need numeric reverse mapping.
type OrderStatusUnion = "PENDING" | "SHIPPED" | "DELIVERED" | "CANCELLED";
function describeOrder(status: OrderStatusUnion): string {
if (status === "SHIPPED") return "Your order is on the way.";
return `Status: ${status}`;
}
console.log(describeOrder("SHIPPED"));
// Output: Your order is on the way.
How it works: The union lists the allowed strings directly. TypeScript rejects any other string at the call site. There is no runtime object, so the compiled JavaScript is smaller. The trade-off is that the strings appear in multiple places, so a rename means editing every occurrence. You can learn more patterns in the Literal Types and Type Aliases & Union Types tutorials.
What Does the Compiled JavaScript Look Like?
It helps to see what TypeScript generates for an enum. Here is a numeric enum and the JavaScript output.
enum Size {
Small,
Medium,
Large,
}
// Compiled output
var Size;
(function (Size) {
Size[Size["Small"] = 0] = "Small";
Size[Size["Medium"] = 1] = "Medium";
Size[Size["Large"] = 2] = "Large";
})(Size || (Size = {}));
How it works: The compiler wraps the enum in a function that fills the object with both directions. Size["Small"] = 0 sets the name-to-value entry, and Size[0] = "Small" sets the reverse entry. String enums skip the reverse entries, so their output is shorter.
Common Mistakes and Best Practices
- Mixing string and numeric members in one enum. TypeScript allows it in some cases but it creates confusing behavior, especially with reverse mapping. Keep an enum all strings or all numbers.
- Using
const enumwithout checkingisolatedModules. Modern bundlers like Vite and esbuild often enableisolatedModules. Aconstenum can then fail to compile or behave unpredictably. Use a regular enum or a union of literals instead. - Assuming numeric enums are safe from out-of-range values. A numeric enum accepts any number at runtime, so
describeOrder(99)may compile if the parameter type is the enum. Add a default case or validate the input. - Forgetting that string enums have no reverse mapping.
OrderStatus["SHIPPED"]works, butOrderStatus["PENDING"]does not return"Pending"as a name. Use a separate map if you need reverse lookups for string enums. - Using enums for values that come from an API as plain strings. You then need casts or mapping functions. A union of string literals fits better because the API values are already the type.
Real-World Example: A Payment Flow
This example uses a string enum for payment status in a function, then shows the same logic with a union of string literals for comparison.
enum PaymentStatus {
Created = "CREATED",
Authorized = "AUTHORIZED",
Captured = "CAPTURED",
Failed = "FAILED",
}
function nextStep(status: PaymentStatus): string {
switch (status) {
case PaymentStatus.Created:
return "Ask the user to authorize.";
case PaymentStatus.Authorized:
return "Capture the payment.";
case PaymentStatus.Captured:
return "Send the receipt.";
case PaymentStatus.Failed:
return "Show the retry screen.";
}
}
console.log(nextStep(PaymentStatus.Authorized));
// Output: Capture the payment.
How it works, line by line. The PaymentStatus enum uses explicit string values, so logs show "AUTHORIZED" instead of a number. The nextStep function accepts status: PaymentStatus, restricting the argument to the four members. The switch covers every case, so the return type stays string. Calling nextStep(PaymentStatus.Authorized) matches the second case and returns the capture message. If you passed a raw string like nextStep("AUTHORIZED"), the compiler would reject it because a string literal is not assignable to the enum type. This safety is the main reason teams use enums for finite sets of values.
For comparison, here is the same idea as a union:
type PaymentStatusUnion = "CREATED" | "AUTHORIZED" | "CAPTURED" | "FAILED";
function nextStepUnion(status: PaymentStatusUnion): string {
switch (status) {
case "CREATED":
return "Ask the user to authorize.";
case "AUTHORIZED":
return "Capture the payment.";
case "CAPTURED":
return "Send the receipt.";
case "FAILED":
return "Show the retry screen.";
}
}
console.log(nextStepUnion("AUTHORIZED"));
// Output: Capture the payment.
Both approaches work. The enum gives you a named type and a single place to change values. The union gives you zero runtime code and seamless JSON interop. Choose based on your team's style and your build tooling.
Summary
- A TypeScript enum names a set of related constant values and removes magic numbers and strings.
- Numeric enums auto-increment by default and support custom values and reverse mapping.
- String enums require explicit values, read well in logs, and have no reverse mapping.
constenums are inlined at compile time but conflict withisolatedModules.- Enums work well as function parameters, and exhaustive switches keep return types safe.
- A union of string literals is often a simpler, lighter alternative; use enums when a named type or reverse mapping helps.
Now that you can define named value sets, continue to the TypeScript Any, Unknown & Never tutorial to learn how to handle values of uncertain or impossible types.
Frequently Asked Questions
Are TypeScript enums bad practice?
They are not bad practice, but they are no longer the default choice for many teams. Enums add runtime code and can interact poorly with const enum and isolatedModules. A union of string literals is often simpler and lighter. Choose enums when a named type or numeric reverse mapping genuinely helps your code.
What is the difference between a numeric enum and a string enum?
A numeric enum stores numbers and auto-increments if you do not set values. It also supports reverse mapping from value to name. A string enum stores string values that you must write explicitly. String enums read better in logs and JSON, but they do not have reverse mapping.
Can I use const enum with modern bundlers?
You can, but you must check whether isolatedModules is enabled. When it is on, const enum can fail or behave unexpectedly because each file is compiled separately. Vite and esbuild often enable this option. To stay safe, use a regular enum or a union of string literals instead.
How do I convert a string to an enum in TypeScript?
TypeScript does not do this automatically. You can write a lookup object that maps the string to the enum member, or use a type guard function that checks the string against the enum values. Keep the check explicit so invalid strings are rejected at runtime.
Why does my numeric enum accept a number that is not a member?
Because numeric enums are typed as the enum, but at runtime any number is assignable in many contexts. The compiler cannot stop a value that comes from outside, such as an API response. Add a runtime check or a default case in your switch to handle unexpected numbers safely.
Practice Exercises
Exercise 1 (Easy): Create a Numeric Enum
Create a numeric enum called Weekday with seven members starting from Monday. Print the value of Wednesday.
Show solution
enum Weekday {
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday,
}
console.log(Weekday.Wednesday);
// Output: 2
Members auto-increment from 0, so Wednesday is 2. Use a custom starting value if you need different numbers.
Exercise 2 (Easy): Create a String Enum
Create a string enum called TrafficLight with Red, Yellow, and Green. Print the value of Yellow.
Show solution
enum TrafficLight {
Red = "RED",
Yellow = "YELLOW",
Green = "GREEN",
}
console.log(TrafficLight.Yellow);
// Output: YELLOW
String enums require explicit values, and the printed value is the readable string "YELLOW".
Exercise 3 (Medium): Use an Enum in a Function
Write a function describeTrafficLight that accepts a TrafficLight and returns a short instruction string. Handle all three cases.
Show solution
enum TrafficLight {
Red = "RED",
Yellow = "YELLOW",
Green = "GREEN",
}
function describeTrafficLight(light: TrafficLight): string {
switch (light) {
case TrafficLight.Red:
return "Stop.";
case TrafficLight.Yellow:
return "Slow down.";
case TrafficLight.Green:
return "Go.";
}
}
console.log(describeTrafficLight(TrafficLight.Green));
// Output: Go.
The parameter type restricts the argument to enum members, and the exhaustive switch keeps the return type as string.
Exercise 4 (Challenge): Convert an Enum to a Union
Take a string enum called OrderStatus with four members. Write an equivalent union of string literals and a function that accepts the union. Show that both compile and produce the same output.
Show solution
enum OrderStatus {
Pending = "PENDING",
Shipped = "SHIPPED",
Delivered = "DELIVERED",
Cancelled = "CANCELLED",
}
type OrderStatusUnion = "PENDING" | "SHIPPED" | "DELIVERED" | "CANCELLED";
function describeOrder(status: OrderStatusUnion): string {
if (status === "SHIPPED") return "On the way.";
return `Status: ${status}`;
}
console.log(describeOrder(OrderStatus.Shipped));
console.log(describeOrder("SHIPPED"));
// Output: On the way.
// Output: On the way.
The string enum value is assignable to the union because its type is the literal "SHIPPED", so both calls work and produce the same output.
Written by Shaikh Abdul Shahid
A Full-Stack Developer with experience in PHP, Laravel, JavaScript, and React.
Founder of Online Learner, sharing practical knowledge and programming tutorials.
Building and maintaining real-world web applications since 2017.
Your Feedback
Help us improve by sharing your thoughts.
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
