Start Coding

Topics

Enums in TypeScript

Enums, short for enumerations, are a powerful feature in TypeScript that allow developers to define a set of named constants. They provide a way to create a collection of related values that can be used as distinct types.

Basic Syntax

To define an enum in TypeScript, use the enum keyword followed by the enum name and a set of comma-separated members:

enum Direction {
    North,
    East,
    South,
    West
}

By default, enums are number-based, starting from 0. You can also assign custom values to enum members:

enum HttpStatus {
    OK = 200,
    NotFound = 404,
    InternalServerError = 500
}

String Enums

TypeScript also supports string enums, which are more readable and debuggable:

enum Color {
    Red = "RED",
    Green = "GREEN",
    Blue = "BLUE"
}

Using Enums

Enums can be used as types and accessed using dot notation:

let myDirection: Direction = Direction.North;
console.log(myDirection); // Output: 0

let statusCode: HttpStatus = HttpStatus.OK;
console.log(statusCode); // Output: 200

let favoriteColor: Color = Color.Blue;
console.log(favoriteColor); // Output: "BLUE"

Reverse Mapping

Numeric enums support reverse mapping, allowing you to get the enum member name from its value:

console.log(Direction[0]); // Output: "North"
console.log(HttpStatus[404]); // Output: "NotFound"

Const Enums

For better performance, you can use const enums. These are erased during compilation and inlined at use sites:

const enum Planet {
    Earth,
    Mars,
    Jupiter
}

let myPlanet = Planet.Earth; // Compiles to: let myPlanet = 0;

Best Practices

  • Use PascalCase for enum names and enum members.
  • Prefer const enums for better performance when possible.
  • Use string enums for better readability and type safety.
  • Consider using union types instead of enums for simple cases.

Related Concepts

To further enhance your TypeScript skills, explore these related topics:

Enums in TypeScript provide a powerful way to define a set of named constants, improving code readability and maintainability. By understanding their syntax and best practices, you can effectively use enums in your TypeScript projects.