Labs ICT
โญ Pro Login

Enums

Enums (enumerations) provide a way to define a set of named constants. You can use numeric enums to create simple constant groups or string enums for more type safety. Enums support reverse mappings to look up values by name, and const enums are compile-time only, making them perfect for configuration and lookup tables.

Enum Types

Use numeric enums when you need to use the values in calculations or comparisons. String enums provide better type safety when the values are used primarily for type checking. Reverse mappings let you access both the value-to-name and name-to-value mappings. Const enums are eliminated at compile time, reducing your bundle size.


// Numeric enum
enum Direction {
    Up = 1,
    Down = 2,
    Left = 3,
    Right = 4
}

console.log(Direction.Up); // 1
console.log(Direction["Up"]); // 1

// Reverse mapping
enum HttpStatus {
    OK = 200,
    Created = 201,
    BadRequest = 400,
    Unauthorized = 401,
    Forbidden = 403,
    NotFound = 404
}

function getMessage(status: HttpStatus): string {
    return HttpStatus[status];
}

// String enum
enum UserRole {
    Admin = "admin",
    User = "user",
    Guest = "guest"
}

// Const enum - compiled away
const enum Directions {
    Up = "up",
    Down = "down",
    Left = "left",
    Right = "right"
}

const direction: Directions = Directions.Up;
    
Try it Yourself โ†’

๐Ÿงช Quick Quiz

Which keyword is used to create an enum?