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