TypeScript Enum


Enum in TypeScript — Simplified

An enum (short for enumeration) is like a labelled set of fixed values. You use it to avoid magic numbers or raw strings floating in your code.


Numeric Enum (Auto Counted)

TypeScript assigns numbers automatically, beginning from 0 unless told otherwise.

enum Direction {   
     North,   // 0   
     East,    // 1   
     South,   // 2   
     West     // 3 
}  

let move = Direction.North; 
Console.log(move); // → 0 

Trying to assign a plain string like 'North' directly will fail because enums are strict.


Numeric Enum (Custom Start)

Want to begin from a different number? No problem. TypeScript will continue from there automatically.

enum Direction {  
     North = 10,   
     East,   // 11   
     South,  // 12   
     West    // 13 
} 

Numeric Enum (Fully Manual)

You can control every value independently. No auto-increment.

enum HttpCode {   
     OK = 200,   
     NotFound = 404,   
     BadRequest = 400,   
     Created = 201 
} 

String Enum

Great for clarity and readability. Every value is a defined string — ideal for logs, APIs, and error messages

enum Weather {   
      Sunny = "Sunny",   
      Rainy = "Rainy",   
      Cloudy = "Cloudy"
 }  

console.log(Weather.Sunny); 

Mixing Types?

You technically can combine numbers and strings in the same enum — but it’s messy and not recommended. Keep enums consistent for sanity and code clarity.


When to Use

  • Roles (enum Role { Admin, Editor, Viewer })
  • Directions (enum Arrow { Left, Right })
  • Status codes (enum Status { Loading, Success, Error })

Prefer Learning by Watching?

Watch these YouTube tutorials to understand TYPESCRIPT Tutorial visually:

What You'll Learn:
  • 📌 TypeScript Tutorial #19 - Enums
  • 📌 Typescript tutorial #11 Enum in TypeScript
Previous Next