Enums in Typescript
Enums in TypeScript are a way to define a set of named constants.
Enums allow you to define a set of named constants. They are useful when you have a fixed set of values that are related to each other.
Example
enum Direction {
Up = 'UP',
Down = 'DOWN',
Left = 'LEFT',
Right = 'RIGHT',
}
// Usage
let direction: Direction = Direction.Up;
console.log(direction); // UP
In the example above, we define an enum Direction
with four named constants Up
, Down
, Left
, and Right
. Each constant has an associated value.
Enums in TypeScript are similar to enums in other programming languages like C# or Java. However, TypeScript enums are more flexible and can have string values, whereas enums in other languages are limited to integer values.
Example: Enum as a Type
Enums can also be used as a type in TypeScript. For example, you can define a function that takes an enum value as an argument:
function move(direction: Direction) {
console.log(`Moving ${direction}`);
}
move(Direction.Left); // Moving LEFT
Example: Check User Access
enum UserRole {
ADMIN = "Admin",
EDITOR = "Editor",
VIEWER = "Viewer",
}
function checkAccess(role: UserRole): void {
if (role === UserRole.ADMIN) {
console.log("You have full access!");
} else {
console.log("Limited access only.");
}
}
checkAccess(UserRole.ADMIN); // You have full access!
Summary
- Use Enums when you have a fixed set of related constants that represent different values
- Use cases: Status codes, User roles/permissions, Configuration options, Application states and etc.