4️⃣ 🧱 TypeScript Collections & Custom Types
Estimated reading: 4 minutes 33 views

🧾 TypeScript — Enums: Complete Guide with Syntax, Examples & Best Practices

🧲 Introduction – What Are Enums in TypeScript?

Enums (short for “enumerations”) in TypeScript are a special feature that lets you define a set of named constants. Enums help organize code and improve readability by giving descriptive names to sets of related values—especially useful for state flags, role types, categories, and directions.

🎯 In this guide, you’ll learn:

  • What enums are and why they are used
  • Syntax for numeric and string enums
  • How to use enums in real-world scenarios
  • Differences between const and regular enums
  • Best practices and common pitfalls

🧾 What Is an Enum?

An enum is a data type that defines a group of named constants. You can use these names instead of magic strings or numbers, making your code more readable and maintainable.

✅ Basic Example:

enum Direction {
  Up,
  Down,
  Left,
  Right
}

let move: Direction = Direction.Up;
console.log(move); // 0

📌 Explanation:

  • Enums are zero-indexed by default.
  • Direction.Up = 0, Direction.Down = 1, and so on.

🔢 Numeric Enums

By default, enum values are auto-incremented numbers starting from 0.

enum Status {
  Success = 1,
  Error,      // 2
  Pending     // 3
}

You can also manually assign values:

enum Role {
  Admin = 10,
  Editor = 20,
  Viewer = 30
}

🔤 String Enums

String enums associate names with fixed string values.

enum LogLevel {
  Info = "INFO",
  Warning = "WARNING",
  Error = "ERROR"
}

let level: LogLevel = LogLevel.Warning;

String enums are useful for APIs, logs, or labels that must not change in value.


📥 Accessing Enum Values

You can access enum values using the enum name:

console.log(Direction.Left); // 2

You can also access the name from the value (only in numeric enums):

console.log(Direction[2]); // "Left"

⚠️ This reverse mapping is not supported in string enums.


💡 Heterogeneous Enums

Enums that mix string and number values.

enum Result {
  Pass = "PASS",
  Fail = 0
}

⚠️ Not recommended unless you have a clear use case.


🧱 Enums in Functions

Enums are ideal for decision-making logic:

function getStatusLabel(status: Status): string {
  switch (status) {
    case Status.Success:
      return "Operation successful";
    case Status.Error:
      return "An error occurred";
    default:
      return "Pending operation";
  }
}

const Enums – For Performance

const enums are inlined at compile-time, removing the actual enum object from the output JS code.

const enum Size {
  Small,
  Medium,
  Large
}

let selectedSize = Size.Medium; // 1

✅ Use const enums for performance-critical code with no need for reverse mapping.


🧪 Real-World Use Cases

  • UI state management (e.g., loading, success, error)
  • HTTP status codes
  • User roles and permissions
  • Feature toggles
  • Direction or navigation logic

⚠️ Common Mistakes & How to Avoid Them

❌ Mistake✅ Solution
Using enum names as stringsAlways use Enum.Name instead of raw strings
Reverse mapping on string enumsOnly numeric enums support reverse mapping
Forgetting default valuesManually assign enum values when order matters
Mixing types in enumsAvoid heterogeneous enums unless necessary

💡 Best Practices for Enums

  • ✅ Use enums to replace magic strings or numbers
  • ✅ Prefer string enums when values must be descriptive or constant
  • ✅ Use const enums for performance and cleaner JS output
  • ✅ Use enums in switch cases to make code more robust and readable
  • ❌ Don’t overuse enums—simple union types may be sufficient in some cases

📌 Summary – Recap & Next Steps

Enums in TypeScript provide a powerful way to group related constants using readable names. They improve code clarity, reduce errors, and are especially useful in managing application state, roles, and logic branches.

🔍 Key Takeaways:

  • Enums define a set of named constants
  • Numeric enums auto-increment, string enums hold fixed values
  • Use const enums for performance
  • Great for simplifying conditional logic

⚙️ Real-world relevance: Widely used in frontend UIs, backend APIs, role-based access control, configuration systems, and more.


❓ FAQs – Enums in TypeScript

❓ What is the difference between an enum and a union type?
Enums are runtime constructs; union types are compile-time only.

❓ Can enums be used with strings?
✅ Yes. Use string enums like enum Color { Red = "RED" }.

❓ Should I use const enums?
✅ Yes, when you don’t need reverse mapping and want faster JS output.

❓ Can I access the name of an enum from a value?
✅ Only for numeric enums, using reverse mapping.

❓ Are enums compiled into JavaScript?
Yes. Unless you use const enums, which are inlined.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

TS Enums / TypeScript — Enums

Or Copy Link

CONTENTS
Scroll to Top