codez.guru

What is an Enum?

An enum (short for enumeration) is a way to define a set of named constants. It helps make your code more readable and self-documenting.


Numeric Enums

By default, TypeScript enums are numeric and auto-incrementing:

enum Direction {
  Up,
  Down,
  Left,
  Right
}

const move = Direction.Left; // 2

You can override the starting value:

enum Status {
  Ready = 1,
  Waiting,
  Complete
}

Here, Waiting becomes 2 and Complete becomes 3.


String Enums

String enums are more explicit and readable:

enum Role {
  Admin = "admin",
  User = "user",
  Guest = "guest"
}

const access = Role.Admin; // "admin"

They’re especially useful for API data or UI logic where values must match specific strings.


Reverse Mapping in Enums

Numeric enums support reverse lookup:

enum Color {
  Red,
  Green,
  Blue
}

console.log(Color[1]); // "Green"

> 🔒 This doesn’t work with string enums (one-way only).


Enums vs Union Types

Consider a union instead of an enum:

type Direction = "up" | "down" | "left" | "right";

When to prefer enums:

  • When using numeric values
  • When reverse mapping is needed
  • When working with legacy code or class-like structures

When to prefer union types:

  • When using strings and simplicity is preferred
  • When working with frontend frameworks or form values

Best Practices

  • Prefer string enums for clarity
  • Avoid const enum in code shared with external tools (can break builds)
  • Consider as const with union types as an alternative:
const Role = {
  Admin: "admin",
  User: "user"
} as const;

type Role = typeof Role[keyof typeof Role];

Summary

  • Enums create named constants for better semantics and safety
  • Use string enums when readability and exact values matter
  • Use union types or as const when enums feel too heavy or inflexible

Next up: Type Assertions and Type Casting — telling TypeScript exactly what you mean when inference isn’t enough.