0
0
Typescriptprogramming~15 mins

Enum member access in Typescript - Deep Dive

Choose your learning style9 modes available
Overview - Enum member access
What is it?
An enum in TypeScript is a way to group related values under a single name. Enum member access means getting or using the specific values or names inside that group. You can access enum members by their names or by their values, depending on how the enum is defined. This helps organize code and makes it easier to work with fixed sets of options.
Why it matters
Without enums and the ability to access their members, programmers would rely on loose constants or strings scattered around the code. This can cause mistakes, like typos or inconsistent values, making programs harder to read and maintain. Enum member access provides a clear, safe way to use fixed sets of values, reducing bugs and improving code clarity.
Where it fits
Before learning enum member access, you should understand basic TypeScript types and variables. After this, you can learn about advanced enum features, like computed members or const enums, and how enums interact with functions and classes.
Mental Model
Core Idea
Enum member access is like looking up a label or a number in a well-organized list to get the matching name or value.
Think of it like...
Imagine a box of crayons where each crayon has a number and a color name. You can pick a crayon by its number or by its color name. Enums let you do the same with code values.
Enum Example:

  enum Colors {
  ┌─────────┬─────────┐
  │ Name    │ Value   │
  ├─────────┼─────────┤
  │ Red     │ 0       │
  │ Green   │ 1       │
  │ Blue    │ 2       │
  └─────────┴─────────┘

Access:
  Colors.Red    → 0
  Colors[0]     → 'Red'
Build-Up - 7 Steps
1
FoundationWhat is an Enum in TypeScript
🤔
Concept: Introduce the basic idea of enums as named sets of values.
In TypeScript, an enum groups related constants under one name. For example: enum Direction { Up, Down, Left, Right } Each member gets a numeric value starting at 0 by default.
Result
You get a named group where Direction.Up equals 0, Direction.Down equals 1, and so on.
Understanding enums as named numbers helps organize related values clearly and safely.
2
FoundationAccessing Enum Members by Name
🤔
Concept: Learn how to get the value of an enum member using its name.
You can get the value of an enum member by writing EnumName.MemberName. For example: console.log(Direction.Up); // prints 0 console.log(Direction.Left); // prints 2
Result
The program prints the numeric values assigned to the enum members.
Accessing by name is the most common way to use enums and keeps code readable.
3
IntermediateAccessing Enum Members by Value
🤔Before reading on: do you think you can get the name of an enum member by using its value? Commit to yes or no.
Concept: Enums in TypeScript support reverse mapping, so you can get the name from the value.
Because TypeScript enums create a two-way map, you can do: console.log(Direction[0]); // prints 'Up' console.log(Direction[2]); // prints 'Left' This works only for numeric enums.
Result
The program prints the names of enum members when accessed by their numeric values.
Knowing reverse mapping lets you convert values back to names, useful for debugging or display.
4
IntermediateString Enums and Member Access
🤔Before reading on: do you think string enums support reverse mapping like numeric enums? Commit to yes or no.
Concept: String enums assign string values and do not support reverse mapping by default.
Example: enum Status { Success = 'SUCCESS', Failure = 'FAILURE' } console.log(Status.Success); // prints 'SUCCESS' console.log(Status['SUCCESS']); // undefined You cannot get the name from the value directly.
Result
Access by name works, but reverse lookup by value does not for string enums.
Understanding this difference prevents confusion and bugs when using string enums.
5
IntermediateComputed and Constant Enum Members
🤔
Concept: Learn how enums can have members with computed or fixed values and how that affects access.
Enums can have members with explicit values or computed values: enum FileAccess { None = 0, Read = 1 << 1, // 2 Write = 1 << 2, // 4 ReadWrite = Read | Write // 6 } Access works the same way: console.log(FileAccess.ReadWrite); // 6 console.log(FileAccess[6]); // 'ReadWrite'
Result
You can access members by name or value even with computed values.
Computed values allow flexible enums while keeping member access consistent.
6
AdvancedEnum Member Access in Type Safety and Code Completion
🤔Before reading on: do you think accessing enum members helps your editor suggest valid options? Commit to yes or no.
Concept: Using enums improves type safety and enables code editors to offer member suggestions.
When you use enums, TypeScript knows the exact set of possible values. For example: function move(direction: Direction) { // ... } move(Direction.Up); // valid move(5); // error Editors show Direction members when typing, reducing mistakes.
Result
Code is safer and easier to write with fewer errors.
Enum member access is not just syntax; it improves developer experience and code quality.
7
ExpertHow Enum Member Access Compiles to JavaScript
🤔Before reading on: do you think enums exist as a special type in JavaScript at runtime? Commit to yes or no.
Concept: TypeScript compiles enums into JavaScript objects with properties for member names and values.
For numeric enums, TypeScript generates code like: var Direction; (function (Direction) { Direction[Direction["Up"] = 0] = "Up"; Direction[Direction["Down"] = 1] = "Down"; Direction[Direction["Left"] = 2] = "Left"; Direction[Direction["Right"] = 3] = "Right"; })(Direction || (Direction = {})); This object supports both name-to-value and value-to-name access.
Result
Enum member access works at runtime because of this generated object structure.
Knowing the compiled output explains why reverse mapping exists only for numeric enums.
Under the Hood
TypeScript enums compile into JavaScript objects where each member name is a property with its value, and for numeric enums, the value is also a property pointing back to the name. This creates a two-way map allowing access by name or value. String enums compile into objects with only name-to-value properties, so reverse lookup is not available.
Why designed this way?
This design balances developer convenience and runtime efficiency. Numeric enums support reverse mapping for debugging and flexibility, while string enums avoid extra code and complexity. The approach fits JavaScript's dynamic nature and keeps enums lightweight.
Enum Object Structure:

┌─────────────────────────────┐
│ Direction (object)          │
│ ┌───────────────┐           │
│ │ 'Up'    : 0   │ ← name to value
│ │ 'Down'  : 1   │           │
│ │ 'Left'  : 2   │           │
│ │ 'Right' : 3   │           │
│ │ 0       : 'Up'│ ← value to name
│ │ 1       : 'Down'│          │
│ │ 2       : 'Left'│          │
│ │ 3       : 'Right'│         │
│ └───────────────┘           │
└─────────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Can you get the name of a string enum member by its value using bracket notation? Commit to yes or no.
Common Belief:You can use bracket notation to get the name from the value for all enums, including string enums.
Tap to reveal reality
Reality:Reverse mapping only works for numeric enums. String enums do not support this and return undefined.
Why it matters:Assuming reverse mapping works for string enums leads to bugs and undefined values at runtime.
Quick: Do enum members always start numbering from 1? Commit to yes or no.
Common Belief:Enum members always start numbering from 1 by default.
Tap to reveal reality
Reality:Enum members start numbering from 0 by default unless explicitly set otherwise.
Why it matters:Wrong assumptions about default values can cause logic errors when comparing or using enum values.
Quick: Is it safe to use any number as an enum value when calling a function expecting an enum? Commit to yes or no.
Common Belief:Any number can be passed where an enum type is expected because enums are just numbers.
Tap to reveal reality
Reality:TypeScript allows any number at runtime, but type checking warns if the number is not a valid enum member, helping catch errors.
Why it matters:Ignoring enum types can cause invalid values to flow through code, leading to unexpected behavior.
Quick: Do enums exist as a special type in JavaScript at runtime? Commit to yes or no.
Common Belief:Enums are a special type in JavaScript just like in TypeScript.
Tap to reveal reality
Reality:Enums do not exist in JavaScript; TypeScript compiles them into plain objects to simulate enum behavior.
Why it matters:Understanding this prevents confusion about runtime behavior and helps debug compiled code.
Expert Zone
1
Numeric enums generate reverse mappings which increase code size; using const enums can avoid this by inlining values.
2
Computed enum members must come after constant members; otherwise, reverse mapping may not work as expected.
3
String enums do not support reverse mapping, so alternative lookup methods are needed if reverse access is required.
When NOT to use
Avoid using enums when the set of values is large or dynamic; use union types or objects instead. Also, prefer const enums for performance when reverse mapping is not needed.
Production Patterns
In production, enums are used for fixed sets like status codes, directions, or flags. Developers often combine enums with switch statements or use them for API response types. Const enums are preferred for performance-critical code to reduce runtime overhead.
Connections
Union Types in TypeScript
Alternative way to represent fixed sets of values without runtime objects.
Understanding enums helps appreciate when to use union types for simpler, compile-time only sets.
Symbolic Constants in C or Java
Enums in TypeScript serve a similar purpose as symbolic constants in other languages.
Knowing enum member access in TypeScript connects to how other languages organize fixed sets of constants.
Database Lookup Tables
Enums resemble lookup tables mapping keys to values in databases.
Recognizing this connection helps understand enums as a lightweight, in-memory lookup mechanism.
Common Pitfalls
#1Trying to get the name of a string enum member by value using bracket notation.
Wrong approach:enum Status { Success = 'SUCCESS', Failure = 'FAILURE' } console.log(Status['SUCCESS']); // undefined
Correct approach:enum Status { Success = 'SUCCESS', Failure = 'FAILURE' } // Use a custom reverse lookup if needed function getStatusName(value: string) { return Object.keys(Status).find(key => Status[key as keyof typeof Status] === value); } console.log(getStatusName('SUCCESS')); // 'Success'
Root cause:Misunderstanding that reverse mapping only works for numeric enums, not string enums.
#2Assuming enum members start at 1 by default.
Wrong approach:enum Colors { Red, Green, Blue } console.log(Colors.Red); // expecting 1 but gets 0
Correct approach:enum Colors { Red = 1, Green, Blue } console.log(Colors.Red); // 1
Root cause:Not knowing that enum numbering starts at 0 unless explicitly set.
#3Passing arbitrary numbers where an enum type is expected without type checking.
Wrong approach:function setDirection(dir: Direction) {} setDirection(5); // no error at runtime
Correct approach:function setDirection(dir: Direction) {} setDirection(Direction.Up); // safe and type-checked
Root cause:Ignoring TypeScript's type system and treating enums as plain numbers.
Key Takeaways
Enums group related named values, making code clearer and safer.
You can access enum members by name to get their value, and for numeric enums, also by value to get their name.
String enums do not support reverse lookup, unlike numeric enums.
TypeScript compiles enums into JavaScript objects that enable this two-way access for numeric enums.
Using enums improves type safety, code completion, and reduces bugs from invalid values.