0
0
Typescriptprogramming~20 mins

Const enums and optimization in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Const Enums for Optimization in TypeScript
📖 Scenario: You are building a simple program to represent directions in a game. You want to use enums to name the directions, but also want to make your code run faster by using const enum.
🎯 Goal: Create a const enum for directions, use it in a function to get the opposite direction, and print the result.
📋 What You'll Learn
Create a const enum called Direction with values Up = 0, Down = 1, Left = 2, Right = 3.
Create a function called getOppositeDirection that takes a Direction and returns the opposite Direction.
Use a switch statement inside getOppositeDirection to return the opposite direction.
Call getOppositeDirection with Direction.Left and print the result.
💡 Why This Matters
🌍 Real World
Enums are used in games, apps, and systems to name fixed sets of options like directions, states, or modes. Using <code>const enum</code> makes the code smaller and faster.
💼 Career
Understanding <code>const enum</code> helps you write efficient TypeScript code, which is valuable for frontend and backend development jobs where performance matters.
Progress0 / 4 steps
1
Create a const enum for directions
Create a const enum called Direction with these exact members and values: Up = 0, Down = 1, Left = 2, Right = 3.
Typescript
Need a hint?

Use the const enum syntax and assign the exact values to each direction.

2
Create a function to get the opposite direction
Create a function called getOppositeDirection that takes a parameter dir of type Direction and returns a Direction.
Typescript
Need a hint?

Define the function with the correct name, parameter, and return type.

3
Implement the switch to return the opposite direction
Inside the getOppositeDirection function, use a switch statement on dir to return the opposite direction: Up returns Down, Down returns Up, Left returns Right, and Right returns Left.
Typescript
Need a hint?

Use a switch with cases for each direction and return the opposite.

4
Call the function and print the result
Call getOppositeDirection with Direction.Left and print the result using console.log.
Typescript
Need a hint?

Use console.log to print the result of calling getOppositeDirection(Direction.Left).