Numeric, String, and Const Enums Explained - Textnotes

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


enum Direction {
Up,
Down,
Left,
Right
}

The values are:

  1. Up = 0
  2. Down = 1
  3. Left = 2
  4. Right = 3

Custom Numeric Values


enum StatusCode {
Success = 200,
NotFound = 404,
ServerError = 500
}

Using Numeric Enums


let responseStatus: StatusCode = StatusCode.Success;

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


enum UserRole {
Admin = "ADMIN",
User = "USER",
Guest = "GUEST"
}

Using String Enums


let role: UserRole = UserRole.Admin;

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


const enum LogLevel {
Info,
Warning,
Error
}

Usage


let level = LogLevel.Error;

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:


type Role = "ADMIN" | "USER" | "GUEST";

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.