tezvyn:

TypeScript Enums: Named Constants for Clarity

AI-drafted, machine-checkedSource: typescriptlang.orgadvanced

TypeScript enums give friendly names to a fixed set of values, like `Status.Success` instead of a magic number. Use them for API response codes or state machines. The footgun: default numeric enums are just numbers at runtime, making them hard to debug.

WHY IT EXISTS Enums were created to replace "magic values"—arbitrary numbers or strings scattered in a codebase—with named, type-safe constants. Using UserRole.Admin is far clearer and less error-prone than checking if user.role === 0 or user.role === "admin".

THE MENTAL MODEL Think of an enum as a closed set of labeled options. It's a way to tell the compiler, "This variable can only be one of these specific things I've named," turning implicit knowledge about a value's meaning into explicit, type-checked code.

HOW IT WORKS TypeScript offers two main kinds. NUMERIC ENUMS assign numbers to each member, auto-incrementing from 0 by default (e.g., Direction.Up is 0, Direction.Down is 1). A key feature is that they create a reverse mapping in the compiled JavaScript, allowing you to look up a member name by its value (e.g., Direction[0] gives "Up"). STRING ENUMS require each member to be initialized with a string (e.g., Direction.Up = "UP"). They don't auto-increment and don't create a reverse mapping, making the compiled code simpler and the runtime values human-readable.

WHEN TO USE IT Use enums for a fixed, known set of values that won't change often. Examples include days of the week, states in a state machine (Pending, InProgress, Complete), or user roles (Admin, Editor, Viewer). String enums are particularly good for values that need to be serialized, like in JSON payloads or database columns, because they remain readable outside your application.

WHEN NOT TO USE IT Avoid enums for data that is dynamic or comes from an external source. If a list of options can change, a union of string literals (e.g., type Status = "pending" | "complete") is often more flexible and doesn't add extra JavaScript at runtime. Also, avoid heterogeneous enums (mixing numbers and strings), as they are confusing and have few practical uses.

ONE CANONICAL EXAMPLE Defining API status codes. Instead of passing around strings or numbers, you can define enum HttpStatus { OK = 200, NOT_FOUND = 404, SERVER_ERROR = 500 }. A function signature handleResponse(status: HttpStatus) is now self-documenting and type-safe; you can't accidentally pass it an invalid code like 501 unless it's part of the enum.

Read the original → typescriptlang.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.