0
0
Typescriptprogramming~15 mins

Why enums are needed in Typescript - See It in Action

Choose your learning style9 modes available
Why enums are needed
📖 Scenario: Imagine you are building a simple app that tracks the status of orders in a store. Each order can be in one of a few fixed states like Pending, Shipped, or Delivered. You want to keep your code clear and avoid mistakes when using these states.
🎯 Goal: You will create a TypeScript enum to represent order statuses. Then you will use this enum to check and print the status of an order. This helps keep your code easy to read and prevents errors from using wrong status values.
📋 What You'll Learn
Create an enum called OrderStatus with values Pending, Shipped, and Delivered
Create a variable called currentStatus and set it to OrderStatus.Pending
Write an if statement to check if currentStatus is OrderStatus.Shipped
Print a message showing the current order status using the enum
💡 Why This Matters
🌍 Real World
Enums are used in apps to represent fixed sets of options like order statuses, user roles, or colors.
💼 Career
Understanding enums helps you write safer and clearer code, a skill valued in many programming jobs.
Progress0 / 4 steps
1
Create the enum for order statuses
Create an enum called OrderStatus with these exact members: Pending, Shipped, and Delivered.
Typescript
Need a hint?

An enum groups related named values. Use enum OrderStatus { Pending, Shipped, Delivered }.

2
Set the current order status
Create a variable called currentStatus and set it to OrderStatus.Pending.
Typescript
Need a hint?

Use let currentStatus = OrderStatus.Pending; to assign the enum value.

3
Check if the order is shipped
Write an if statement that checks if currentStatus is equal to OrderStatus.Shipped.
Typescript
Need a hint?

Use if (currentStatus === OrderStatus.Shipped) { ... } to compare enum values.

4
Print the current order status
Print the message The current order status is: Pending by using console.log and the enum value OrderStatus.Pending.
Typescript
Need a hint?

Use console.log(`The current order status is: ${OrderStatus[currentStatus]}`); to print the status name.