Skip to main content

Enumerations (Enums)

An enum is a special class that represents a group of pre-defined constants. It allows developers to define a set of named constraints, making the code much more readable and preventing simple typographical strings from dominating the logical systems.

Numeric Enums​

By default, Enums initialize the very first item to the number 0 and auto-increment up.

enum Direction {
Up, // Value is 0
Down, // Value is 1
Left, // Value is 2
Right // Value is 3
}

// Accessing the enum state
let move: Direction = Direction.Up;

console.log(move); // 0

You can optionally manually set the starter number!

enum ResponseCodes {
NotFound = 404,
Success = 200,
ServerCrash = 500
}

String Enums​

Strictly locking strings is often safer and more readable during active network debugging than trying to figure out what numeric 0 translates to.

enum Role {
Admin = "ADMIN",
Editor = "EDITOR",
Viewer = "VIEWER"
}

// In the database or parameters, we enforce one of these string types!
function assignRole(userRole: Role) {
if(userRole === Role.Admin) {
console.log("Full Authority Checked.");
}
}

assignRole(Role.Editor);