Enums

Enums (short for enumerations) in TypeScript are a feature that allows you to define a set of named constants. They provide a human-readable way to represent a set of constant values, which might otherwise be represented as numbers or strings.

Example 1: Game Controls

Letโ€™s say you have a game where you have to perform an action based on whether the user has pressed the up, down, left, or right arrow key.

enum Direction {
    Up,
    Down,
    Left,
    Right
}

function doSomething(keyPressed: Direction) {
    // do something.
}

doSomething(Direction.Up);

This makes the code cleaner and easier to understand. At runtime, the values stored are still numbers (0, 1, 2, 3).

2. Runtime Values of Enums

Let's log the runtime value of Direction.Up:

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

By default, enums get values starting from 0 and incrementing by 1 for each subsequent member.

3. Customizing Enum Values

You can customize the values of enums:

enum Direction {
    Up = 1,
    Down,   // 2
    Left,   // 3
    Right   // 4
}

function doSomething(keyPressed: Direction) {
    // do something.
}

doSomething(Direction.Down);

4. Using String Values

Enums can also be represented as strings:

enum Direction {
    Up = "UP",
    Down = "Down",
    Left = "Left",
    Right = "Right"
}

function doSomething(keyPressed: Direction) {
    // do something.
}

doSomething(Direction.Down);

5. Common Use Case in Express

Enums are commonly used in frameworks like Express to represent status codes:

enum ResponseStatus {
    Success = 200,
    NotFound = 404,
    Error = 500
}

app.get("/", (req, res) => {
    if (!req.query.userId) {
        res.status(ResponseStatus.Error).json({});
    }
    // and so on...
    res.status(ResponseStatus.Success).json({});
});

Enums provide a convenient way to define a set of related constants and improve code readability and maintainability. They are widely used in various scenarios, including game development, web frameworks, and API development.

Last updated

Was this helpful?