0
0
Typescriptprogramming~15 mins

Reverse mapping in numeric enums in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Reverse mapping in numeric enums
📖 Scenario: Imagine you are creating a simple traffic light system in TypeScript. Each light color has a number code. You want to be able to find the color name from the number code and also get the number code from the color name.
🎯 Goal: Build a numeric enum for traffic light colors and use reverse mapping to find the color name from a number code.
📋 What You'll Learn
Create a numeric enum called TrafficLight with exact members: Red = 1, Yellow = 2, Green = 3
Create a variable called lightNumber and set it to 2
Use reverse mapping to get the color name from lightNumber and store it in a variable called lightName
Print the value of lightName to the console
💡 Why This Matters
🌍 Real World
Enums with reverse mapping are useful in programs where you need to convert between codes and names, like traffic lights, status codes, or menu options.
💼 Career
Understanding enums and reverse mapping helps in writing clear and maintainable TypeScript code, a skill valuable for frontend and backend developers working with typed JavaScript.
Progress0 / 4 steps
1
Create the numeric enum
Create a numeric enum called TrafficLight with these exact members and values: Red = 1, Yellow = 2, Green = 3.
Typescript
Need a hint?

Use the enum keyword and assign numbers to each color.

2
Create the number variable
Create a variable called lightNumber and set it to the number 2.
Typescript
Need a hint?

Use let to create the variable and assign the value 2.

3
Use reverse mapping to get the color name
Use reverse mapping on the TrafficLight enum with lightNumber to get the color name. Store the result in a variable called lightName.
Typescript
Need a hint?

Use bracket notation with the enum and the number variable to get the name.

4
Print the color name
Print the value of lightName to the console using console.log.
Typescript
Need a hint?

Use console.log(lightName) to show the color name.