Last Updated : 20 Mar, 2025
TypeScript Enums allows you to create a list of constants (unchanging variables) and give them easy-to-remember names. These names make your code easier to read and understand by grouping related values together under one name. Enums can use both numbers and text, so you can choose what works best for your code.
TypeScript provides two main types of enums: Numeric and String enums.
1. Numeric EnumsNumeric enums are the default in TypeScript. Each member of a numeric enum is assigned a numeric value, starting from 0 by default, but you can customize these values as needed.
Default Numeric Enums:In default numeric enums, the first member is assigned the value 0, and each subsequent member is incremented by 1.
JavaScript
enum Direction {
Up,
Down,
Left,
Right
}
let move: Direction = Direction.Up;
console.log(move);
Output:
0Initialized Numeric Enums:
You can assign a specific value to the first member, and subsequent members will auto-increment from that value.
JavaScript
enum Direction {
Up = 1,
Down,
Left,
Right
}
let move: Direction = Direction.Up;
console.log(move);
Output:
1Fully Initialized Numeric Enums:
Each member can be assigned a unique numeric value, independent of its position.
JavaScript
enum Direction {
Up = 1,
Down = 3,
Left = 5,
Right = 7
}
let move: Direction = Direction.Up;
console.log(move);
Output:
12. String Enums
String enums allow you to assign string values to each member, providing meaningful names that enhance code clarity.
JavaScript
enum Direction {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT"
}
let move: Direction = Direction.Up;
console.log(move);
Output:
"UP"3. Heterogeneous Enums
TypeScript also supports heterogeneous enums, where you can mix both numeric and string values in the same enum. However, this is not commonly used because it can make the code less consistent and harder to maintain.
JavaScript
enum Status {
Active = 1,
Inactive = "INACTIVE",
Pending = 2,
Cancelled = "CANCELLED"
}
let currentStatus: Status = Status.Active;
console.log(currentStatus); // Output: 1
let cancelledStatus: Status = Status.Cancelled;
console.log(cancelledStatus); // Output: "CANCELLED"
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4