0
0
Typescriptprogramming~10 mins

Enum member access in Typescript - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Enum member access
Define Enum
Access Member by Name
Get Member Value
Use Value in Code
Access Member by Value (Reverse Lookup)
Get Member Name
Use Name in Code
This flow shows how to define an enum, access its members by name to get values, and also access members by value to get names.
Execution Sample
Typescript
enum Color {
  Red = 1,
  Green,
  Blue
}

let c = Color.Green;
console.log(c);
Defines an enum Color with members, accesses the Green member, and prints its value.
Execution Table
StepActionEvaluationResult
1Define enum Color with Red=1, Green=2, Blue=3N/AColor = {1: 'Red', 2: 'Green', 3: 'Blue', Red: 1, Green: 2, Blue: 3}
2Access Color.GreenColor.Green2
3Assign Color.Green to variable cc = 2c = 2
4Print cconsole.log(c)2
5Access Color[2] (reverse lookup)Color[2]'Green'
6Print Color[2]console.log(Color[2])'Green'
💡 All enum members accessed; program ends after printing values.
Variable Tracker
VariableStartAfter Step 3Final
Colorundefined{Red:1, Green:2, Blue:3, 1:'Red', 2:'Green', 3:'Blue'}{Red:1, Green:2, Blue:3, 1:'Red', 2:'Green', 3:'Blue'}
cundefined22
Key Moments - 2 Insights
Why does Color.Green equal 2 instead of 1?
Because Red is explicitly set to 1, Green automatically gets the next number, 2, as shown in execution_table step 1 and 2.
How can we get the name 'Green' from the value 2?
By using reverse lookup Color[2], which returns 'Green' as shown in execution_table step 5.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of Color.Blue?
A2
B3
C1
Dundefined
💡 Hint
Check step 1 where enum members and their values are defined.
At which step is the variable c assigned a value?
AStep 3
BStep 4
CStep 2
DStep 5
💡 Hint
Look at the action column for assignment to c.
If we change Red to 5, what would Color.Green's value be?
A5
B1
C6
D2
💡 Hint
Enum auto-increments from the previous value, see step 1 for how values are assigned.
Concept Snapshot
enum EnumName { Member1 = value1, Member2, ... }
Access member value: EnumName.Member1
Reverse lookup: EnumName[value] returns member name
Members auto-increment if not assigned
Use enum values for readable constants
Full Transcript
This example shows how to define an enum in TypeScript with members Red, Green, and Blue. Red is set to 1 explicitly, so Green and Blue get 2 and 3 automatically. We assign Color.Green to variable c and print it, which outputs 2. We also demonstrate reverse lookup by accessing Color[2] to get the string 'Green'. This helps understand how enum members can be accessed by name or by value.