TypeScript Enum

TypeScript is a superset of JavaScript that provides optional static typing, making it easier to write complex code. One of the features that TypeScript provides is the ability to define enums. An enum, short for enumeration, is a way of giving names to a set of values. In this lesson, we will go over what TypeScript enums are, how they work, and how to use them with code examples.

What is an Enum in TypeScript?

In TypeScript, an enum is a set of named values that represent a set of related constants. Enums are used to make code more readable, maintainable, and less error-prone. With enums, you can define a set of named constants that can be used throughout your code.

Here is an example of an enum in TypeScript:

enum Direction {
  Up,
  Down,
  Left,
  Right,
}

In this example, we define an enum called Direction. The enum keyword is used to define the enum. Inside the curly braces, we define the different values that the enum can take. In this case, the values are Up, Down, Left, and Right. Each of these values is assigned a default number value starting from 0. If you want to assign specific values to each enum member, you can do so by manually specifying their values.

In this case, Up has a value of 1, Down has a value of 2, and so on.

How to use an Enum in TypeScript

Once you have defined an enum, you can use it in your code like this:

let direction: Direction = Direction.Up;

In this example, we declare a variable called direction of type Direction. We assign it the value Direction.Up, which is the first value in the Direction enum.

You can also use enums in switch statements:

switch (direction) {
  case Direction.Up:
    // Do something if direction is Up
    break;
  case Direction.Down:
    // Do something if direction is Down
    break;
  case Direction.Left:
    // Do something if direction is Left
    break;
  case Direction.Right:
    // Do something if direction is Right
    break;
}

In this example, we use a switch statement to check the value of the direction variable. We compare it to the different values in the Direction enum using the case keyword. Depending on the value of direction, we execute different blocks of code.

Conclusion

In conclusion, enums are a powerful feature of TypeScript that make it easier to define named constants in your code. They help make your code more readable, maintainable, and less error-prone. With enums, you can define a set of named constants that can be used throughout your code. We hope this lesson has helped you understand what TypeScript enums are and how to use them.