0
0
Typescriptprogramming~20 mins

When enums add unnecessary runtime code in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
When enums add unnecessary runtime code
📖 Scenario: Imagine you are building a simple app that needs to represent a few fixed colors. You want to use TypeScript enums but learn how they add extra code when compiled. This project will help you see how to avoid that extra code by using a different approach.
🎯 Goal: You will create a TypeScript enum for colors, then replace it with a simpler constant object to avoid unnecessary runtime code. You will see the difference in output.
📋 What You'll Learn
Create a TypeScript enum called Colors with three colors: Red, Green, and Blue.
Create a constant object called ColorsConst with the same color keys and string values.
Write a function getColorName that takes a color value and returns its name using the enum.
Write a function getColorNameConst that takes a color value and returns its name using the constant object.
Print the results of calling both functions with the value 1.
💡 Why This Matters
🌍 Real World
Enums are useful for fixed sets of values but can add extra code that is not always needed. Using constant objects or union types can keep your code smaller and faster.
💼 Career
Understanding how enums compile helps you write efficient TypeScript code, which is important for frontend and backend development jobs.
Progress0 / 4 steps
1
Create a TypeScript enum for colors
Create a TypeScript enum called Colors with these entries: Red = 0, Green = 1, and Blue = 2.
Typescript
Need a hint?

Use the enum keyword followed by the name Colors. Inside curly braces, list the colors with their numeric values.

2
Create a constant object for colors
Create a constant object called ColorsConst with keys Red, Green, and Blue and values "Red", "Green", and "Blue" respectively.
Typescript
Need a hint?

Use const ColorsConst = { Red: "Red", Green: "Green", Blue: "Blue" } as const; to create a readonly object.

3
Write functions to get color names
Write a function called getColorName that takes a parameter color of type Colors and returns the color name using the enum. Also write a function called getColorNameConst that takes a parameter color of type keyof typeof ColorsConst and returns the color name from ColorsConst.
Typescript
Need a hint?

Use the enum as an index to get the name in getColorName. Use the key to get the value from ColorsConst in getColorNameConst.

4
Print the results of both functions
Write two console.log statements to print the results of calling getColorName(1) and getColorNameConst("Green").
Typescript
Need a hint?

Use console.log(getColorName(1)) and console.log(getColorNameConst("Green")) to print the color names.