SyntaxStudy
Sign Up
TypeScript Numeric and String Enums
TypeScript Beginner 1 min read

Numeric and String Enums

Enums (enumerations) are a TypeScript feature that lets you define a set of named constants. They make code more readable by replacing magic numbers or strings with descriptive names. TypeScript supports three kinds of enums: numeric, string, and heterogeneous (mixed), though heterogeneous enums are rarely useful in practice. Numeric enums start at 0 by default and auto-increment. You can specify a custom starting value or set individual member values explicitly. Numeric enums are bidirectionally mapped at runtime — you can look up both the value from the name and the name from the value. This reverse mapping can be useful for debugging but also means numeric enums have a larger runtime footprint than string enums. String enums require each member to be initialised with a string literal. They have no reverse mapping, which means the compiled code is simpler. String enums are generally preferred over numeric enums because their values are human-readable in logs and network payloads, making debugging much easier. The trade-off is slightly more verbose initialisation.
Example
// Numeric enum — auto-increments from 0
enum Direction {
    North,   // 0
    East,    // 1
    South,   // 2
    West,    // 3
}

console.log(Direction.North); // 0
console.log(Direction[0]);    // "North" — reverse mapping

// Custom start value
enum HttpStatus {
    Ok          = 200,
    Created     = 201,
    BadRequest  = 400,
    Unauthorized = 401,
    NotFound    = 404,
    ServerError = 500,
}

function handleResponse(status: HttpStatus): string {
    switch (status) {
        case HttpStatus.Ok:       return "Success";
        case HttpStatus.NotFound: return "Resource not found";
        default:                  return `Status ${status}`;
    }
}

// String enum — preferred for readability
enum LogLevel {
    Debug   = "DEBUG",
    Info    = "INFO",
    Warning = "WARNING",
    Error   = "ERROR",
}

function log(level: LogLevel, message: string): void {
    console.log(`[${level}] ${message}`);
}

log(LogLevel.Info, "Server started");
log(LogLevel.Error, "Unhandled exception");

// Enum as a type
function isError(level: LogLevel): boolean {
    return level === LogLevel.Error;
}

console.log(isError(LogLevel.Warning)); // false