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?