0
0
Typescriptprogramming~5 mins

Why enums are needed in Typescript

Choose your learning style9 modes available
Introduction

Enums help us give names to a set of related values. This makes code easier to read and less error-prone.

When you have a fixed set of options, like days of the week.
When you want to avoid using many magic numbers or strings in your code.
When you want to group related constants under one name.
When you want to make your code easier to understand for others.
When you want to prevent invalid values by limiting choices.
Syntax
Typescript
enum Name {
  Option1,
  Option2,
  Option3
}

Each option inside an enum gets a numeric value by default, starting at 0.

You can assign specific values to options if you want.

Examples
This enum represents four directions with default numeric values 0, 1, 2, 3.
Typescript
enum Direction {
  Up,
  Down,
  Left,
  Right
}
Here, we assign specific numbers to each status for clarity.
Typescript
enum Status {
  Active = 1,
  Inactive = 0,
  Pending = 2
}
This enum uses strings instead of numbers for better readability.
Typescript
enum Color {
  Red = "RED",
  Green = "GREEN",
  Blue = "BLUE"
}
Sample Program

This program defines weekdays as an enum. It shows how to use enum values and a function that checks if a day is weekend (which returns false here).

Typescript
enum Weekday {
  Monday,
  Tuesday,
  Wednesday,
  Thursday,
  Friday,
  Saturday,
  Sunday
}

function isWeekend(day: Weekday): boolean {
  return day === Weekday.Saturday || day === Weekday.Sunday;
}

console.log(Weekday.Monday);  // prints 0
console.log(isWeekend(Weekday.Monday));  // prints false
OutputSuccess
Important Notes

Enums make your code safer by limiting possible values.

Using enums helps avoid typos in strings or numbers.

TypeScript enums can be numeric or string-based depending on your needs.

Summary

Enums group related values with friendly names.

They improve code readability and reduce errors.

Use enums when you have a fixed set of options.