Enums and Constants: Managing Defined States

6 min read

Welcome back, coder! ☕️👋

Today we are tackling a problem that has plagued humanity since the dawn of... well, since the dawn of variables.

Imagine you are building a traffic light controller. You see a variable in the legacy code: let currentLight = 2.

What does 2 mean?

  • Is it Red?
  • Is it Green?
  • Is it Self-Destruct? 💥

This is what we call a Magic Number. It is "magic" because it appears out of nowhere, has no obvious meaning, and might cast a dark spell on your production environment if you mess it up.

In TypeScript, we use Enums and Constants to banish magic numbers and replace them with readable, meaningful names. Let's bring some order to the chaos. 🛡️


1. Numeric Enums: Counting with Names

🧐 The Definition

An enum (short for Enumeration) is a data structure that defines a set of named constants. A Numeric Enum stores these constants as numbers under the hood.

😫 The Problem

Without enums, you define states using loose numbers.

typescript
// ❌ The Bad Way
function moveCharacter(direction: number) {
  if (direction === 0) console.log("Going Up");
  else if (direction === 1) console.log("Going Down");
}

moveCharacter(0); // What is 0? North? Sky? The Ceiling?

If you accidentally type moveCharacter(99), TypeScript won't stop you (if typed as generic number), and your character might glitch into the void.

💡 The Solution

We group these values into a named set.

typescript
// ✅ The TypeScript Way
enum Direction {
  Up,    // 0
  Down,  // 1
  Left,  // 2
  Right  // 3
}

function moveCharacter(dir: Direction) {
  if (dir === Direction.Up) {
     console.log("🚀 Going Up!");
  }
}

moveCharacter(Direction.Up);

⚙️ How it Works & Industry Practice

By default, TypeScript assigns the number 0 to the first member and increments by 1 for the rest.

You can also start the count wherever you want. This is useful for matching database IDs.

typescript
enum StatusCode {
  OK = 200,
  BadRequest = 400,
  Unauthorized, // Will become 401 automatically
  PaymentRequired // Will become 402
}

console.log(StatusCode.Unauthorized); // Output: 401

⚠️ Under the Hood (The Weird Part):
Numeric Enums are unique because they possess a "Reverse Mapping".
You can look up the name using the value, and the value using the name.

typescript
console.log(StatusCode[400]); // Output: "BadRequest"

Fun Fact: TypeScript tries hard to not emit runtime code, but Enums are one of the few features that actually generate a real JavaScript object in your compiled code. It's not a ghost; it's real! 👻


2. String Enums: Clearer Debugging and Readability

🧐 The Definition

String Enums are enums where each member has to be initialized with a string literal.

😫 The Problem

Numeric enums are efficient, but terrible for debugging logs.
Imagine looking at your server logs and seeing:
User Role Changed to: 4

Is 4 "Admin"? Or is 4 "Banned"? You have to open your code, find the Enum definition, and count on your fingers. 🖐️

💡 The Solution

String Enums act as a strict contract but serialize to readable strings.

typescript
enum UserRole {
  Admin = "ADMIN",
  Editor = "EDITOR",
  Guest = "GUEST"
}

// In your app
const currentUser = {
  name: "Sarah",
  role: UserRole.Admin
};

// In your logs
console.log(JSON.stringify(currentUser)); 
// Output: {"name":"Sarah", "role":"ADMIN"}

Now, when you debug, you see "ADMIN", not some cryptic integer.

🏗️ Industry Standard

String Enums are heavily used when communicating with APIs or Databases where the value needs to be human-readable.

Key Difference: String Enums do NOT have a reverse mapping. You cannot do UserRole["ADMIN"] to get the variable name.


3. The as const Assertion for Immutable Literal Values

🧐 The Definition

as const is a const assertion. It tells TypeScript: "Take this object or array, and make it purely immutable. Narrow the types from general strings/numbers to their exact literal values."

😫 The Problem

Enums are great, but they have baggage:

  1. They generate extra runtime code (IIFEs).
  2. Some developers (and linters) dislike TypeScript-specific syntax that isn't standard JavaScript.
  3. Standard Objects are mutable.
typescript
const Config = {
  Theme: "Dark",
  Language: "English"
};

// TypeScript thinks Config.Theme is a generic 'string'.
// It assumes you might want to change it later:
Config.Theme = "Light"; // Allowed, but maybe we didn't want this allowed.

💡 The Solution: The "Object Enum"

This is the modern trend in the TypeScript ecosystem. We use a standard JavaScript object and lock it down with as const.

typescript
const GameState = {
  Start: "START",
  Paused: "PAUSED",
  GameOver: "GAME_OVER"
} as const; 👈 // The Magic Spell

// usage
const current: string = GameState.Start;

When you hover over GameState.Start, TypeScript doesn't say it's a string. It says the type is exactly "START". It is read-only.

🧠 The Big Brain Move: Extracting Types

You might be thinking, "But with Enums I could use the Enum name as a Type! How do I do that here?"

We use a chaotic looking, but standard utility chain: keyof typeof.

typescript
// 1. The Value Object
const LogLevel = {
  ERROR: "error",
  WARN: "warn",
  INFO: "info"
} as const;

// 2. The Type Definition
// Translated: Give me the values of the keys of the type of LogLevel
type LogLevel = typeof LogLevel[keyof typeof LogLevel];

// 3. Usage
function logMessage(level: LogLevel, msg: string) {
  // 'level' can ONLY be "error" | "warn" | "info"
}

logMessage("error", "Database on fire"); // ✅
logMessage("fatal", "System explode");   // ❌ Error: "fatal" is not assignable to type LogLevel

🏆 Industry Verdict: Enum vs as const

  • Use Enums if you want simple, auto-incrementing numbers or if you are migrating from C#/Java and like the syntax.
  • Use as const objects if you want to keep your runtime code clean (closer to vanilla JS), improve tree-shaking, and strictly control literal types. This is currently preferred in many modern React/Node TS codebases.

📝 Summary

Feature Best Used For Runtime Impact
Numeric Enum Internal state, bitwise flags, simple counters. Creates an Object with reverse mapping.
String Enum API responses, Readable Logs, Config values. Creates an Object.
Object as const Modern TS apps, reducing bundle size, exact literal types. Zero (It's just a standard JS object).

📚 References & Further Reading


Next up, we will dive into Functions and Typing signatures. Don't let your states get undefined! Happy Coding! 🚀

Challenge

You are building a monitoring module for a large-scale web application. To ensure code clarity, type safety, and maintainability, you must replace all "magic numbers" and strings with structured, named constants.

Your task is to implement three different methods for creating these constants based on their specific use cases:

  1. Numeric Enum for Status Codes: Create a numeric enum named HttpStatusCode to represent API response codes. This enum will be used internally for logic that might require reverse mapping (looking up the name from the numeric value).

    • OK should be 200
    • BadRequest should be 400
    • NotFound should be 404
  2. String Enum for Log Levels: For human-readable logs, create a string enum named LogLevel. Using strings ensures that logs sent to a monitoring service are immediately understandable without needing a lookup table.

    • Info should be the string "INFO"
    • Warning should be "WARN"
    • Error should be "ERROR"
  3. as const Object for User Actions: For performance-critical parts of the application, you need to define user actions. To avoid the runtime overhead of enums and ensure the smallest possible bundle size, use a standard JavaScript object with the as const assertion. Call it UserAction.

    • Login should be the string "USER_LOGIN"
    • Logout should be "USER_LOGOUT"
    • CreatePost should be "CREATE_POST"
  4. Create a Union Type: From the UserAction object, derive a union type alias named UserActionType. This type should represent any possible user action string from the object.

  5. Function Signature: Define a function createLogEntry that accepts the following parameters in order:

    • level of type LogLevel.
    • action of type UserActionType.
    • statusCode of type HttpStatusCode.

Expected result

Your final code should contain the following, in valid TypeScript:

  1. A HttpStatusCode numeric enum with OK, BadRequest, and NotFound members assigned to 200, 400, and 404 respectively.
  2. A LogLevel string enum with Info, Warning, and Error members initialized with their corresponding string values ("INFO", "WARN", "ERROR").
  3. A constant object named UserAction defined with as const, containing Login, Logout, and CreatePost keys.
  4. A type alias UserActionType that correctly resolves to the union type "USER_LOGIN" | "USER_LOGOUT" | "CREATE_POST".
  5. A function named createLogEntry with the precise signature: (level: LogLevel, action: UserActionType, statusCode: HttpStatusCode) => void.
  6. A constant badRequestName correctly initialized using the reverse mapping of HttpStatusCode to retrieve the string "BadRequest" from the value 400.
typescript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.