DEV Community

Cover image for Understanding Enums in TypeScript.
Lingaraj H U
Lingaraj H U

Posted on

Understanding Enums in TypeScript.

  • Have you ever found yourself juggling multiple values in your code, wishing there was a more organized way to manage them?

  • Imagine having a list of predefined options that are both human-readable and machine-understandable. This is where enums come to the rescue!!!

Enums, short for enumerations, are a powerful feature in TypeScript that allows you to define a set of named constants. They're particularly useful when you have a fixed set of values that a variable can take.

Let's dive into enums and see how they can make your code more readable and maintainable.

  • Here's a simple enum definition:

Basic enum

enum Direction {
  North,
  East,
  South,
  West
}

// Using the enum
let myDirection: Direction = Direction.North;
console.log(myDirection); // Output: 0
Enter fullscreen mode Exit fullscreen mode
  • By default, enums are number-based, starting from 0. But you can customize this:
enum Direction {
  North = 1,
  East,  // 2
  South, // 3
  West   // 4
}

// if you initialize first variable by a particular value then
// the next variable will maintain the order of value 
// assigned to first variable 

enum Direction {
  North = 100,
  East,  // 101
  South, // 102
  West   // 103
}

Enter fullscreen mode Exit fullscreen mode
  • String Enums

TypeScript also supports string enums, which are more descriptive

enum Color {
  Red = "RED",
  Green = "GREEN",
  Blue = "BLUE"
}

let myFavoriteColor: Color = Color.Blue;
console.log(myFavoriteColor); // Output: "BLUE"
Enter fullscreen mode Exit fullscreen mode
  • Heterogeneous Enums

You can mix string and numeric members, but it's generally not recommended:

enum Mixed {
  Number = 1,
  String = "String"
}
Enter fullscreen mode Exit fullscreen mode
  • Reverse Mappings Numeric enums come with reverse mappings, allowing you to get the enum member name from its value:
enum Weekday {
  Monday,
  Tuesday,
  Wednesday
}

console.log(Weekday[0]); // Output: "Monday"

enum Direction {
  North = 100,
  East,  // 101
  South, // 102
  West   // 103
}

console.log(Direction[101]); // output: "East"
Enter fullscreen mode Exit fullscreen mode

When to Use Enums?

  • Enums come in handy in several scenarios:

Representing a fixed set of options: Like days of the week, card suits, or HTTP status codes.
Improving code readability: Instead of using magic numbers or strings, enums provide meaningful names.
Type safety: TypeScript ensures you only use valid enum values, catching errors at compile-time.

Some common use cases for enums include:

  • Defining a set of error codes or status codes.
  • Representing a set of colors, sizes, or other categorical values.
  • Defining a set of roles or permissions in an application.

Here's a practical example:

Payment Status Enum

  • In a payment processing system, we need to handle different payment statuses, such as "Pending", "Success", "Failed", etc. We can define an enum to represent these statuses:
enum PaymentStatus {
  Pending = 'pending',
  Success = 'success',
  Failed = 'failed',
  Refunded = 'refunded'
}

// Using the Enum:
// Now, let's use this `enum` in a payment processing function:

function processPayment(status: PaymentStatus) {
  switch (status) {

    case PaymentStatus.Pending:
      // Handle pending payment
      break;

    case PaymentStatus.Success:
      // Handle successful payment
      break;

    case PaymentStatus.Failed:
      // Handle failed payment
      break;

    case PaymentStatus.Refunded:
      // Handle refunded payment
      break;

    default:
      throw new Error('Invalid payment status');

  }
}

Enter fullscreen mode Exit fullscreen mode
  • Enums in TypeScript offer a clean way to define a set of named constants. They enhance code readability, provide type safety, and are especially useful when working with fixed sets of values.
  • As you progress in your TypeScript journey, you'll find enums to be a valuable tool in your programming toolkit.

Thank you for reading... Hope you learnt something new today :)

Top comments (0)