Enum Types
In this page:
Numeric Enums
A numeric enum assigns a numeric value to each of its members, and by default the first member starts at zero with each later member incrementing automatically. You can also set the starting value explicitly, and the rest will count up from there.
Example: Numeric Enums
enum Direction {
Up,
Down,
Left,
Right,
}
console.log(Direction.Up, Direction.Right);
String Enums
String enums give each member an explicit string value instead of an auto-incrementing number, written directly in the enum definition. They're often easier to debug because logging or serializing the value shows a meaningful word rather than an opaque number.
Example: String Enums
enum Status {
Active = "ACTIVE",
Inactive = "INACTIVE",
}
console.log(Status.Active);
Using Enums in Functions
Enums can be used directly as a function parameter's type, which restricts callers to only the values actually defined in that enum. This prevents a caller from passing an arbitrary number or string where only one of a known, fixed set of options makes sense.
Example: Using Enums in Functions
enum Role {
Admin,
Editor,
Viewer,
}
function checkAccess(role: Role): void {
console.log(`Access level: ${Role[role]}`);
}
checkAccess(Role.Admin);
Enum Comparisons
Enum members can be compared using the normal equality operators, just like any other value, since each member is really just a constant under the hood. This makes it easy to branch program behavior based on which known enum value is currently held.
Example: Enum Comparisons
enum Status {
Active,
Inactive,
}
let current: Status = Status.Active;
console.log(current === Status.Active);
Enums in Switch Statements
Enums pair especially well with switch statements, since each case label can represent exactly one known enum member. This keeps code that needs to handle several distinct states organized and makes it easy to see at a glance whether every option is covered.
Example: Enums in Switch Statements
enum Status {
Active,
Inactive,
Pending,
}
let current: Status = Status.Pending;
switch (current) {
case Status.Active:
console.log("Active");
break;
case Status.Pending:
console.log("Pending");
break;
default:
console.log("Other");
}
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: