Enums In Typescript

 Enums in TypeScript allow developers to define a set of named constants. Enums provide a way to organize related values and make code more readable and maintainable. Here's an explanation of enums in TypeScript:

Enum Basics:

enum Direction {
    Up,
    Down,
    Left,
    Right
}

let userDirection: Direction = Direction.Up;
console.log(userDirection); // Output: 0

In this example:

  • We define an enum called Direction with four members: Up, Down, Left, and Right.
  • By default, enums are assigned numeric values starting from 0. In this case, Up is assigned the value 0, Down is assigned 1, and so on.
  • We assign a value from the Direction enum to a variable userDirection.

Custom Enum Values:

enum Direction {
    Up = 1,
    Down,
    Left = 5,
    Right
}

let userDirection: Direction = Direction.Left;
console.log(userDirection); // Output: 5

In this example:

  • We assign custom numeric values to some enum members. Here, Up is explicitly assigned 1, Down automatically gets assigned 2 (incremented from the previous value), Left is assigned 5, and Right automatically gets assigned 6 (incremented from the previous value).
  • When we assign Direction.Left to userDirection, it holds the value 5.

Accessing Enum Values:

console.log(Direction.Up); // Output: 1
console.log(Direction[5]); // Output: Left
  • Enum values can be accessed by their keys or by their corresponding numeric values.

String Enums:

enum Fruit {
    Apple = "apple",
    Banana = "banana",
    Orange = "orange"
}

let userFruit: Fruit = Fruit.Banana;
console.log(userFruit); // Output: banana
  • Enums can also have string values. String enums provide better readability when the enum values need to be descriptive strings.

Heterogeneous Enums:

enum UserResponse {
    Yes = 1,
    No = "NO"
}
  • Enums can have a mix of string and numeric values. However, it's generally recommended to keep enums consistent for better clarity.

Enums with Computed Values:

enum Color {
    Red = 1,
    Green = Math.random(),
    Blue = 4
}
  • Enum members can have computed values, but these values must be constant expressions.

Enum Member Types:

  • Enum members can have different types. While the default type is number, enum members can be of type number, string, or even a computed value.

Enum Initialization:

  • Enum members can be initialized explicitly or implicitly. If the value of the first member is not explicitly initialized, it defaults to 0, and subsequent members are auto-incremented from that value. However, explicitly setting the value of the first member affects the auto-incrementation of subsequent members.

Reverse Mapping:

  • Enums in TypeScript support reverse mapping, which means you can access the enum member name from its value. This is particularly useful when working with numeric enums.

Example of Reverse Mapping:

enum Direction {
    Up,
    Down,
    Left,
    Right
}

let userDirection: Direction = Direction.Up;
console.log(Direction[userDirection]); // Output: Up

Enum Comparisons:

  • Enums can be compared using both their numeric values and their member names. TypeScript allows comparing enum values directly, either numerically or by name.

Example of Enum Comparisons:

enum Status {
    Pending,
    Approved,
    Rejected
}

let currentStatus: Status = Status.Pending;

if (currentStatus === Status.Pending) {
    console.log("Application is pending.");
}

Enums as Flags:

  • Enums in TypeScript can be used as flags by combining multiple enum values using bitwise operators (| for OR, & for AND). This allows representing combinations of values as a single value.

Example of Enums as Flags:

enum Permission {
    Read = 1,
    Write = 2,
    Execute = 4
}

let userPermission: Permission = Permission.Read | Permission.Write;

if (userPermission & Permission.Read) {
    console.log("User has read permission.");
}

if (userPermission & Permission.Write) {
    console.log("User has write permission.");
}

Const Enums:

  • TypeScript provides const enums, which are enums whose values are entirely removed during compilation. This can result in more efficient code, especially when enums are used in contexts that are purely for type checking and not for runtime code generation.

Example of Const Enums:

const enum Status {
    Active,
    Inactive
}

let currentStatus: Status = Status.Active;

Use Cases:

  • Enums are useful for representing fixed sets of related constants, such as days of the week, directions, status codes, etc.
  • They provide a more expressive way of dealing with such values, improving code readability and maintainability.

Enums in TypeScript are a powerful tool for representing and working with fixed sets of related constants. Understanding their features and capabilities allows developers to leverage enums effectively in their TypeScript projects.

Enums in TypeScript provide a way to represent a set of related constants, improving code readability and maintainability. They're particularly useful when dealing with a fixed set of values that are logically related to each other.

Post a Comment

0 Comments