Numeric, String, and Const Enums Explained
Learn how to use enums in TypeScript to define a fixed set of named constants. This module explains numeric enums, string enums, const enums, and best practices for using enums in real-world applications
1. Numeric Enums
Numeric enums are the default enum type in TypeScript. By default, the first value starts at 0 and increments by 1.
Basic Numeric Enum Example
The values are:
- Up = 0
- Down = 1
- Left = 2
- Right = 3
Custom Numeric Values
Using Numeric Enums
Numeric enums allow reverse mapping from value to name, which can be useful in debugging.
2. String Enums
String enums require each member to be explicitly assigned a string value.
String Enum Example
Using String Enums
String enums provide better readability and are safer for logging and API communication.
3. Const Enums
Const enums are optimized enums that are removed during compilation and replaced with inline values in the generated JavaScript.
Const Enum Example
Usage
During compilation, this is converted directly to the numeric value, improving performance and reducing output size.
4. Usage Guidelines
Use numeric enums when you need automatic value increments or reverse mapping.
Use string enums when values need to be meaningful and human-readable, especially for APIs and logging.
Use const enums for performance-critical applications where enum values are fixed and should not exist at runtime.
Avoid overusing enums for simple values where union types may be more appropriate.
Example alternative:
This can sometimes be simpler and more flexible than enums.
Conclusion
Enums provide a structured way to define constant values in TypeScript. Understanding numeric, string, and const enums helps developers choose the right approach for different scenarios and build more maintainable applications.