Member-only story
TypeScript : Understanding Enums
Enums are a powerful feature in TypeScript that allows developers to define a set of named constants. They make code more readable, prevent magic values, and help maintain type safety.
In this post, we’ll explore what enums are, how to use them, and why they are so useful!
What is an Enum?
An enum (short for enumeration) is a TypeScript feature that allows you to define a collection of related values with meaningful names.
Why Use Enums?
✔ Makes code more readable.
✔ Prevents hardcoded magic values.
✔ Provides type safety by restricting allowed values.
Enum Example in TypeScript
1️⃣ Numeric Enums (Default Behavior)
By default, enums are numeric, starting from 0
and auto-incrementing.
enum Role {
User, // 0
Admin, // 1
SuperAdmin // 2
}
console.log(Role.Admin); // Output: 1
console.log(Role[2]); // Output: "SuperAdmin"
TypeScript assigns 0
to User
, 1
to Admin
, and 2
to SuperAdmin
automatically.
2️⃣ String Enums (More Readable)
You can explicitly assign string values to enum members.
enum Status {
Pending = "PENDING",
Approved = "APPROVED",
Rejected = "REJECTED"
}
console.log(Status.Pending); // Output: "PENDING"
console.log(Status.Rejected); // Output: "REJECTED"