🔷 TypeScript Q8 / 101

What is enum in TypeScript?

AI-Powered Answer ✓ Answered

Enums, short for enumerations, are a powerful feature in TypeScript (and many other languages like C#, Java) that allow a developer to define a set of named constants. They provide a way to give more meaningful names to sets of numeric or string values, making your code more readable and maintainable.

What is an Enum?

At their core, enums are a collection of related values, often representing different states or options. TypeScript supports several types of enums: numeric, string, and heterogeneous.

Numeric Enums

This is the default type. If you don't explicitly assign values, the first member gets the value 0, and subsequent members are auto-incremented from there.

typescript
enum Direction {
  Up,
  Down,
  Left,
  Right
}

let go: Direction = Direction.Up; // go is 0
console.log(Direction.Right);    // Prints 3

You can also manually assign numeric values. Subsequent unassigned members will continue to auto-increment from the last assigned value.

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

console.log(HttpStatus.OK); // Prints 200

Numeric enums also support reverse mapping from enum value to enum name at runtime, meaning you can access the name of a member given its value.

typescript
enum Status { Success = 1, Error = 2 }
let statusName: string = Status[2]; // statusName is "Error"

String Enums

String enums are similar to numeric enums, but the members are assigned string values. They offer better readability during debugging and when printing the value.

typescript
enum LogLevel {
  ERROR = "ERROR",
  WARN = "WARN",
  INFO = "INFO",
  DEBUG = "DEBUG"
}

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

log(LogLevel.ERROR, "An error occurred!"); // Prints: [ERROR] An error occurred!

String enums do not have auto-incrementing behavior and do not support reverse mapping like numeric enums.

Heterogeneous Enums (Mixed)

Enums can mix numeric and string members, though this is generally not recommended as it can lead to confusion and is rarely useful.

typescript
enum Mixed {
  No = 0,
  Yes = "YES"
}

When to use Enums

  • Defining a set of known constants: Like days of the week, months, status codes, user roles, etc.
  • Improving code readability: Using descriptive names instead of 'magic numbers' or raw strings.
  • Ensuring type safety: The compiler can check if you're using a valid enum member where an enum type is expected.
  • Refactoring: Changing an enum member's value only requires updating one place.

Const Enums

By adding the const modifier to an enum, you tell TypeScript that the enum should be inlined at compile-time, meaning that no JavaScript object will be generated for the enum at runtime. This can lead to slightly more optimized JavaScript output, especially for very large enums, by avoiding runtime overhead.

typescript
const enum Colors {
  Red,
  Green,
  Blue
}

let c: Colors = Colors.Green;

// When compiled, `c` will directly become `1` wherever `Colors.Green` was used.

A limitation of const enums is that they cannot have reverse mappings, as the enum object itself doesn't exist at runtime.

Summary

Enums in TypeScript provide a structured way to work with named constants, enhancing code clarity, maintainability, and type safety. Whether you choose numeric or string enums depends on your specific use case, with const enums offering a performance optimization by inlining values at compile-time.