codewithjohn.dev
Published on

Understanding TypeScript Enums

Enums in typescript represent a group of constant variables that are closely related They are very similar to javascript objects. when you run your code through the typescript compiler enums get compiled to javascript objects, In Typescript we can have both numeric and string-based enums.

Numeric enums

To create an enum in Typescript use the enum keyword, followed by the name of the enum. Then create a curly bracket {} block, Then specify the enum members inside, like this:

example_one.ts
enum Direction {
  North = 1,
  East,
  South,
  West,
};

function printDirection(direction : Direction) {
  console.log(`Direction is ${direction}`);
}

printSize(Direction.North); // 👉️ Direction is 1

In the above snippet we use the number 1 as the value of the first member of the Direction enum. This assigns the number 1 to be the value of North All of the following members are auto-incremented by default from that point on. In other words, Direction.North has the value 1, Direction.East has 2,Direction.South has 3, and Direction.West has 4.

But It is optional we could leave off the initializers entirely and it becomes like below.

example_two.ts
enum Direction {
  North,
  East,
  South,
  West,
  };

Here, Direction.North would have the value 0, Direction.East Would have 1, etc.

You can also assign unique number values for each enum value. Therefore the values will not be incremented.

example_three.ts
enum Direction{
  North = 10,
  East = 20,
  South = 30,
  West = 40,
}

console.log(Direction.North);  👉️ 10

console.log(Direction.South);  👉️ 30

String Enums

TypeScript compiler defaults to assigning numbers to enum members as we have seen above, but you can override this to make a string enum. They are enums that have string values for each member, especially if you need
human-readable meaning they are useful.

example_five.ts
enum Direction {
  North = "North",
  East = "East",
  South = "South",
  West = "West",
};

function printDirection(direction : Direction) {
  console.log(`Direction is ${direction}`);
}

printDirection(Direction.North); // 👉️ Direction is North

Conclusion

TypeScript enums are a powerful feature that can improve the clarity, readability, and maintainability of your code.In this tutorial you have learned about Typescript enums you also saw the syntax and practical examples of how they are used.