0
0
Typescriptprogramming~3 mins

Why String enums in Typescript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if a tiny typo in your code could silently break your program? String enums stop that from happening.

The Scenario

Imagine you are writing a program where you need to handle different user roles like 'admin', 'editor', and 'viewer'. You write these roles as plain strings everywhere in your code.

At first, it seems easy, but as your program grows, you have to type these strings many times in different places.

The Problem

Typing the same strings repeatedly is slow and easy to mess up. A small typo like 'admn' instead of 'admin' can cause bugs that are hard to find.

Also, if you want to change a role name, you have to search and update every place manually, which is tiring and error-prone.

The Solution

String enums let you define all your string values in one place with clear names. Then, you use these names everywhere in your code.

This way, you avoid typos because the computer checks your code. If you want to change a string, you do it once in the enum, and it updates everywhere.

Before vs After
Before
if (role === 'admin') {
  // do admin stuff
}

if (role === 'admn') {
  // typo causes bug
}
After
enum UserRole {
  Admin = 'admin',
  Editor = 'editor',
  Viewer = 'viewer'
}

if (role === UserRole.Admin) {
  // do admin stuff
}
What It Enables

String enums make your code safer, easier to read, and simpler to maintain by grouping related string values under clear names.

Real Life Example

Think of a traffic light system where states like 'red', 'yellow', and 'green' are used. Using string enums ensures you only use these exact states everywhere, preventing mistakes like 'gren' or 'redd'.

Key Takeaways

Typing strings repeatedly leads to errors and slow updates.

String enums group related strings with clear names in one place.

This reduces bugs and makes code easier to maintain.