TypeScript: Enums

In TypeScript, an enum is a way to define a set of named constants. This can be useful when you want to represent a set of related values that have a specific order or meaning.

Declaration

Here's an example of how to declare an enum in TypeScript:

enum Color {
    Red,
    Green,
    Blue
}

StackBlitz Link

In this example, the Color enum defines three named constants: Red, Green, and Blue. By default, these constants are assigned values of 0, 1, and 2, respectively. You can also specify the values explicitly:

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

StackBlitz Link

In this example, the Color enum defines three named constants with values of 1, 2, and 4, respectively.

Sample Usage

You can use enums in TypeScript to represent a set of related values. For example, you might use an enum to represent the days of the week:

enum DayOfWeek {
    Sunday,
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday
}

let today: DayOfWeek = DayOfWeek.Wednesday;
console.log(today); // Output: 3

StackBlitz Link

In this example, the DayOfWeek enum defines seven named constants that represent the days of the week. The today variable is declared as a DayOfWeek type and is assigned the value of Wednesday.

You can also use enums with switch statements to perform different actions based on the value of a variable:

enum Direction {
    Up,
    Down,
    Left,
    Right
}

function move(direction: Direction) {
    switch (direction) {
        case Direction.Up:
            console.log("Moving up");
            break;
        case Direction.Down:
            console.log("Moving down");
            break;
        case Direction.Left:
            console.log("Moving left");
            break;
        case Direction.Right:
            console.log("Moving right");
            break;
        default:
            console.log("Invalid direction");
    }
}

move(Direction.Up); // Output: "Moving up"
move(Direction.Left); // Output: "Moving left"

StackBlitz Link

In this example, the Direction enum defines four named constants that represent the directions that an object can move. The move function takes a Direction parameter and uses a switch statement to perform different actions based on the value of the parameter.

Overall, enums can be a useful tool in TypeScript when you need to represent a set of related values that have a specific order or meaning. They can help make your code more readable and maintainable by providing meaningful names for constants instead of using raw numbers or strings.


View Parent Post: TypeScript: Everything You Need to Know