DEV Community

Cover image for Typescript Enums
Shagun Mistry
Shagun Mistry

Posted on

Typescript Enums

Enums, short for enumerations, are a powerful feature in TypeScript that allow you to define a set of named constants. This can be incredibly useful when you want to represent a limited set of choices or options within your code.

Enums can make your code more readable, maintainable, and less prone to errors.

Imagine you're building a simple online store. You need to represent the different payment methods your customers can choose from:

// Without enums
const PAYMENT_METHOD_CARD = "card";
const PAYMENT_METHOD_PAYPAL = "paypal";
const PAYMENT_METHOD_APPLEPAY = "applepay";

// ... later in your code ...
if (paymentMethod === PAYMENT_METHOD_CARD) {
  // Process card payment
} else if (paymentMethod === PAYMENT_METHOD_PAYPAL) {
  // Process Paypal payment
}
Enter fullscreen mode Exit fullscreen mode

This approach works, but it's a bit verbose and prone to typos.

This is where Enums come handy!

// Using enums
enum PaymentMethod {
  Card = "card",
  Paypal = "paypal",
  ApplePay = "applepay",
}

// ... later in your code ...
if (paymentMethod === PaymentMethod.Card) {
  // Process card payment
} else if (paymentMethod === PaymentMethod.Paypal) {
  // Process Paypal payment
}
Enter fullscreen mode Exit fullscreen mode

Here's why enums are so awesome:

  • Readability: Instead of using magic strings, you have clearly defined names like PaymentMethod.Card which make your code much easier to understand.
  • Type Safety: TypeScript will flag any errors if you try to use an invalid payment method, preventing runtime issues.
  • Maintainability: If you need to add a new payment method, you only need to add it to the enum definition, ensuring consistency across your codebase.

Let's put it into action with a practical code example:

enum PaymentMethod {
  Card = "card",
  Paypal = "paypal",
  ApplePay = "applepay",
}

function processPayment(paymentMethod: PaymentMethod) {
  if (paymentMethod === PaymentMethod.Card) {
    console.log("Processing card payment...");
  } else if (paymentMethod === PaymentMethod.Paypal) {
    console.log("Processing Paypal payment...");
  } else if (paymentMethod === PaymentMethod.ApplePay) {
    console.log("Processing ApplePay payment...");
  }
}

processPayment(PaymentMethod.Paypal); // Output: Processing Paypal payment...
Enter fullscreen mode Exit fullscreen mode

Isn't that neat?

Enums bring structure and clarity to your code, making it easier to manage and less error-prone.

Top comments (1)

Collapse
 
lexlohr profile image
Alex Lohr

Only recently I started a discussion about the shortcomings of enums in TS. Maybe that helps adding a bit of perspective.