Working with TypeScript Enums

24 Jun 2023 Balmiki Mandal 0 Typescript

Working with TypeScript Enums

Enums are a powerful feature of TypeScript that can help improve the readability of your code. With enums, you can define a set of named constants that can be referenced by developers when writing code. This makes it easier to maintain code, since all values are standardized and stored in one place.

Enums are declared using the keyword ‘enum’ followed by a unique identifier name and a variable list of members. Each member has an associated numerical value, starting with 0 and incrementing by 1 for each successive member.

For example, if you wanted to create an enum for the days of the week, you could do so as follows:

enum DaysOfTheWeek {
  'SUNDAY',
  'MONDAY',
  'TUESDAY',
  'WEDNESDAY',
  'THURSDAY',
  'FRIDAY',
  'SATURDAY'
}

You can access any member of an enum using dot notation. For example, if you wanted to access the value of Sunday, you would do so by writing DaysOfTheWeek.Sunday. This returns 0 because it is the first member of the enum.

In addition to using dot notation, you can also use the index of a member. So if you wanted to access the value of Wednesday, you could write DaysOfTheWeek[3] which returns 3 because it is the fourth member of the enum.

You can also use enums to store other types of information. For example, you could create an enum with a string value for each member. To do this, you would use the following syntax:

enum Colors {
  'RED' = "red",
  'BLUE' = "blue",
  'GREEN' = "green"
}

You can access the string value for each member using the same dot notation or index syntax as before. For example, if you wanted to access the string value for Red, you would write Colors.Red which returns 'red'.

Enums are a great feature of TypeScript that can make your code more readable and maintainable. Give them a try next time you’re writing code in TypeScript!

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.