What is an Enum?
An enum (enumeration) is a set of named constants. Instead of using loose strings like"loading", "error", we use predefined values that the editor can verify.
Basic Syntax
Real Example: Loading States
From our project, we define the 4 possible loading states:main.ts
Using the Enum
main.ts
Why Use Enums Instead of Strings?
Without Enum (Error-Prone)
With Enum (Safe)
Advantages of Enums
1. Autocompletion
Your editor suggests all valid values:2. Easy Refactoring
Change a value once, it updates everywhere:3. Documentation
You can see all possible values in one place:4. Type Safety
TypeScript prevents you from using invalid values:Using Enums with Switch Statements
Enums work perfectly withswitch statements:
main.ts
updateUI function:
main.ts
String Enums vs Numeric Enums
String Enums (Recommended)
We use string values for better debugging:Numeric Enums
TypeScript can also use numbers (less common):Real-World State Management Flow
Here’s how our enum flows through the app:When to Use Enums
Use enums when you have:- Fixed set of options: Loading states, user roles, order statuses
- Values that won’t change often: HTTP methods, file types
- Related constants: Colors, sizes, priorities
Good Use Cases
Debugging with Enums
String enums make console.log output more readable:Next Steps
- Async/Await - Use enums to track loading states
- Interfaces - Combine enums with interfaces
- DOM Manipulation - Update UI based on enum states