Show List

Enums in TypeScript

Enums in TypeScript allow you to define a set of named constants with a numeric value. Enums are a way to represent a collection of related values as a single entity, and make it easier to work with sets of values in your code.

Here's a simple example of an enum in TypeScript:

enum Direction {
  Up,
  Down,
  Left,
  Right
}

let direction = Direction.Up;
console.log(direction); // 0

In this example, the Direction enum defines a set of named constants Up, Down, Left, and Right. By default, the first constant has a value of 0, the second has a value of 1, and so on. You can access the values of the constants in the enum by using the dot notation, like Direction.Up.

You can also assign specific values to the constants in the enum, like this:

enum Color {
  Red = 1,
  Green = 2,
  Blue = 4
}

let color = Color.Green;
console.log(color); // 2

In this example, the Color enum defines a set of named constants Red, Green, and Blue with specific values. The value of Red is 1, the value of Green is 2, and the value of Blue is 4. You can access the values of the constants in the enum in the same way as before.

You can also use enums to define a mapping between named constants and their values, making it easier to work with related values in your code. For example:

enum Response {
  No = 0,
  Yes = 1
}

function respond(recipient: string, message: Response): void {
  console.log(`The recipient ${recipient} responded ${message}`);
}

respond("Princess Caroline", Response.Yes);
// The recipient Princess Caroline responded 1

In this example, the Response enum defines a mapping between the named constants No and Yes and their numeric values. The respond function takes two arguments: a recipient string and a message of type Response. The function uses the Response enum to log a message indicating the recipient's response.

Enums are a useful tool in TypeScript for representing collections of related values as a single entity. They make it easier to work with sets of values, and provide a way to map between named constants and their values, improving the readability and maintainability of your code.


    Leave a Comment


  • captcha text