0
0
Typescriptprogramming~3 mins

Why enums are needed in Typescript - The Real Reasons

Choose your learning style9 modes available
The Big Idea

What if a tiny typo in your code could cause big bugs that are hard to find?

The Scenario

Imagine you are writing a program that handles different user roles like 'admin', 'editor', and 'viewer'. You type these role names as plain text everywhere in your code.

At first, it seems easy, but as your program grows, you have to remember the exact spelling and case of each role every time.

The Problem

Typing role names as plain text is slow and error-prone. A small typo like 'Admin' instead of 'admin' can cause bugs that are hard to find.

Also, if you want to change a role name, you must search and update every place manually, which is painful and risky.

The Solution

Enums let you define a set of named constants in one place. You use these names everywhere in your code, so you never mistype them.

This makes your code easier to read, safer, and easier to maintain.

Before vs After
Before
if (userRole === 'admin') {
  // do admin stuff
}
After
enum UserRole { Admin, Editor, Viewer }
if (userRole === UserRole.Admin) {
  // do admin stuff
}
What It Enables

Enums enable you to write clear, consistent code that avoids mistakes and is easy to update.

Real Life Example

In a web app, using enums for user roles helps prevent bugs caused by typos and makes it simple to add new roles later without breaking existing code.

Key Takeaways

Typing strings manually leads to errors and hard-to-maintain code.

Enums group related constants in one place for safer use.

Using enums improves code clarity and reduces bugs.