TypeScript Enums: Your Label Maker for Code! 🏷️
The Story of the Label Maker
Imagine you have a magical label maker. Instead of writing “Red”, “Blue”, “Green” every time you need a color, you just press a button and pop — the perfect label comes out!
That’s exactly what Enums do in TypeScript. They give names to values so your code becomes:
- Easier to read
- Harder to mess up
- Super organized
🎯 What is an Enum?
Think of an enum like a menu at a restaurant. Instead of saying “I want item number 2”, you say “I want the Pizza”!
enum Food {
Pizza,
Burger,
Salad
}
let myLunch = Food.Pizza;
Why is this awesome?
- You can’t accidentally type
"Pizzaa"(typo!) - Your editor suggests options for you
- Everyone on your team uses the same names
📊 Numeric Enums: The Counting Labels
By default, enums are like a numbered list. TypeScript counts starting from 0.
enum Direction {
Up, // 0
Down, // 1
Left, // 2
Right // 3
}
console.log(Direction.Up); // 0
console.log(Direction.Right); // 3
Custom Starting Number
You can start from any number you want!
enum StatusCode {
Success = 200,
NotFound = 404,
Error = 500
}
console.log(StatusCode.NotFound); // 404
Real Life Example:
- TV channels (1, 2, 3…)
- HTTP status codes (200, 404, 500)
- Game levels (1, 2, 3…)
🔤 String Enums: The Word Labels
Sometimes numbers don’t make sense. What if you want actual words?
enum Color {
Red = "RED",
Green = "GREEN",
Blue = "BLUE"
}
console.log(Color.Red); // "RED"
Why Use String Enums?
graph TD A[String Enums] --> B[Easy to Debug] A --> C[Readable Logs] A --> D[Clear Meaning] B --> E["See 'ERROR' not '2'"] C --> F["Console shows words"] D --> G["Code explains itself"]
Example: App States
enum AppState {
Loading = "LOADING",
Ready = "READY",
Error = "ERROR"
}
let currentState = AppState.Loading;
console.log(currentState); // "LOADING"
⚡ Const Enums: The Super-Fast Labels
Regular enums create extra code when TypeScript compiles. Const enums are different — they disappear!
const enum Size {
Small = 1,
Medium = 2,
Large = 3
}
let mySize = Size.Medium;
// Compiles to: let mySize = 2;
The Magic Trick
graph TD A[const enum Size] --> B[TypeScript Code] B --> C[Compiler Magic] C --> D["Just the number: 2"] style D fill:#90EE90
Before (TypeScript):
const enum Speed {
Slow = 10,
Fast = 100
}
let s = Speed.Fast;
After (JavaScript):
let s = 100; // Enum gone!
When to use const enums:
- You want faster, smaller code
- You don’t need to look up enum names at runtime
🤔 Enums vs Union Types: The Great Choice
TypeScript gives you two ways to make limited choices. Let’s compare!
Option 1: Enum
enum Status {
Active = "active",
Inactive = "inactive",
Pending = "pending"
}
function setStatus(s: Status) {
console.log(s);
}
setStatus(Status.Active);
Option 2: Union Type
type Status = "active" | "inactive" | "pending";
function setStatus(s: Status) {
console.log(s);
}
setStatus("active");
Which One Should You Pick?
graph TD A{What do you need?} --> B[Need to use in other files?] A --> C[Want smallest code?] A --> D[Need reverse lookup?] B --> E[Use Enum] C --> F[Use Union Type] D --> G[Use Enum]
| Feature | Enum | Union Type |
|---|---|---|
| Extra JS code | Yes | No |
| Reverse lookup | Yes | No |
| Easier refactoring | Yes | Harder |
| Smaller bundle | No | Yes |
Quick Rule:
- Enum → When you need organization and features
- Union → When you want simplicity and small code
🎮 Putting It All Together
Let’s build a simple game character system!
// Numeric enum for levels
enum Level {
Beginner = 1,
Intermediate = 2,
Expert = 3
}
// String enum for character class
enum CharacterClass {
Warrior = "WARRIOR",
Mage = "MAGE",
Healer = "HEALER"
}
// Const enum for speed (disappears!)
const enum Speed {
Slow = 5,
Normal = 10,
Fast = 20
}
// Create a character
let hero = {
name: "Alex",
level: Level.Beginner,
class: CharacterClass.Mage,
speed: Speed.Normal
};
console.log(hero.class); // "MAGE"
console.log(hero.level); // 1
🌟 Key Takeaways
- Enums = Named constants (like labels!)
- Numeric enums count automatically (0, 1, 2…)
- String enums use readable words
- Const enums vanish after compiling (super fast!)
- Union types are simpler but less powerful
🎉 You Did It!
You now understand TypeScript Enums! Think of them as your code’s label maker — keeping everything organized, readable, and mistake-free.
Next time you have a set of fixed choices (colors, states, directions), reach for an enum! Your future self will thank you. 🚀