Enums are a powerful feature of TypeScript, providing an easy way to define named constants that make your code more readable and maintainable. This article explores both basic and advanced usages of enums, including practical examples and best practices.
What are Enums in TypeScript?
Enums (enumerations) are a way to organize collections of related values as named constants, enhancing code clarity and preventing the use of magic numbers or strings.
Basic Enum Example:
enum Direction {
Up,
Down,
Left,
Right
}
let move: Direction = Direction.Up;
console.log(move); // Output: 0
Numeric vs. String Enums
Numeric Enums:
By default, enums start numbering at 0, but you can customize this:
enum Status {
Pending = 1,
InProgress,
Completed
}
console.log(Status.InProgress); // Output: 2
String Enums:
Useful for debugging and readability:
enum LogLevel {
ERROR = "ERROR",
WARN = "WARN",
INFO = "INFO"
}
console.log(LogLevel.ERROR); // Output: "ERROR"
Advanced Enum Usage
Enum as Types
Enums can be directly used as types in function parameters, promoting type safety:
enum UserRole {
Admin,
User,
Guest
}
function setUserRole(role: UserRole) {
// implementation
}
setUserRole(UserRole.Admin); // Correct usage
// setUserRole("Admin"); // Error
Const Enums
Const enums are completely removed during compilation, improving performance:
const enum Color {
Red,
Green,
Blue
}
let favoriteColor = Color.Blue;
console.log(favoriteColor); // Output: 2 (inlined during compilation)
Enum with Bitwise Operators
Enums can represent bit flags, providing efficient ways to combine multiple settings:
enum Permissions {
Read = 1 << 0,
Write = 1 << 1,
Execute = 1 << 2
}
let userPermissions = Permissions.Read | Permissions.Write;
// Check permissions
let canExecute = (userPermissions & Permissions.Execute) === Permissions.Execute;
console.log(canExecute); // false
Best Practices
- Prefer string enums for improved readability.
- Use const enums when performance optimization is critical.
- Clearly document the intent behind your enums, especially when used with bitwise operations.
Enums offer clarity, type safety, and performance improvements to your TypeScript applications.
Have you used enums in an interesting way? Share your experiences in the comments below! π
Top comments (0)