TypeScript Course
TypeScript
/
Beginner

Numeric Enums

Definition

An Enum (Enumeration) is a feature added by TypeScript that allows you to define a set of named constants. By default, enums are number-based, starting at 0 and auto-incrementing.

Explain Like I'm New

Enums are like assigning human-readable names to confusing numbers. Instead of trying to remember that User Role `1` is Admin and `2` is Guest, you create an Enum. In your code you just type `Role.Admin`, and TS translates it to `1` under the hood.

Real World Example

Handling directional movement in a game (`Direction.Up`, `Direction.Down`) or API status codes (`Status.Success`, `Status.NotFound`).

Common Use Cases

  • •Replacing 'Magic Numbers' in code
  • •Grouping related constants

Interactive Example

// Default starting at 0
enum Direction {
  Up,    // 0
  Down,  // 1
  Left,  // 2
  Right  // 3
}

let playerMove = Direction.Left; 
console.log(playerMove); // Output: 2

// Custom starting point
enum HttpCode {
  OK = 200,
  BadRequest = 400,
  NotFound = 404
}

console.log(HttpCode.NotFound); // 404

// REVERSE MAPPING (Only works for numeric enums!)
console.log(Direction[1]); // Output: "Down"

Interview Questions

basic

  • What value does the first item in a numeric enum have if unassigned?

intermediate

  • Can you assign a custom number to start the incrementing?

advanced

  • What is Reverse Mapping in numeric enums?

Flash Cards

Question

Can you assign a custom number?

Click to reveal answer
Answer

Yes. If you do `enum Role { Admin = 5, Guest }`, Guest will automatically become `6`.

Question

What is Reverse Mapping?

Click to reveal answer
Answer

Unlike normal objects, numeric enums compile into a two-way mapping in JavaScript. If `Direction.Up` equals `1`, then `Direction[1]` evaluates back to the string `'Up'`.