Enums, short for enumerations, are a powerful feature in TypeScript that allow you to define a set of named constants. They provide a human-readable way to represent values that might otherwise be numbers or strings, making your code easier to read and maintain.
1. Why Use Enums?
Consider a game where you need to perform actions based on user input: pressing the up, down, left, or right arrow key. How would you represent these inputs in your code?
- As strings:
"UP"
,"DOWN"
,"LEFT"
,"RIGHT"
- As numbers:
1
,2
,3
,4
Both work, but they are not very readable or self-explanatory. This is where enums shine.
2. Example: Using Enums for Directions
You can define an enum for directions like this:
enum Direction {
Up,
Down,
Left,
Right
}
function doSomething(keyPressed: Direction) {
// perform an action based on the direction
}
doSomething(Direction.Up);
✅ Advantages:
- The code is cleaner and more readable.
- You avoid "magic numbers" or ambiguous strings.
💡 At runtime, by default, enums store numeric values starting from 0
. For example:
console.log(Direction.Up); // Output: 0
console.log(Direction.Right); // Output: 3
3. Customizing Enum Values
You can change the numeric values if needed:
enum Direction {
Up = 1,
Down, // 2
Left, // 3
Right // 4
}
Or you can use string enums for even clearer semantics:
enum Direction {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT"
}
doSomething(Direction.Down);
4. Using Enums in Express Applications
Enums are also useful in web applications, such as defining HTTP response status codes:
enum ResponseStatus {
Success = 200,
NotFound = 404,
Error = 500
}
app.get("/", (req, res) => {
if (!req.query.userId) {
res.status(ResponseStatus.Error).json({ error: "User ID missing" });
return;
}
res.status(ResponseStatus.Success).json({ msg: "Request successful" });
});
✅ Benefits:
- Improves readability (
ResponseStatus.Success
is clearer than200
). - Reduces mistakes caused by hardcoding numbers or strings.
5. Summary
- Enums provide named constants for better code clarity.
- Default enums are numeric, starting from 0, but you can customize numbers or use strings.
- Enums are widely used in TypeScript, including Express applications for status codes and other fixed sets of values.
Using enums is a simple but effective way to make your TypeScript code more maintainable and readable.
Top comments (0)