Topics in this subject
TypeScript 2 min read Updated 11 Aug 2026

Literal Types and Enums

Restricting variables to exact values and organizing constant values.

🧑‍🏫 Sabse pehle — simple mein samjho#

Normal variables mein hum bolte hain "yeh koi bhi string ho sakti hai". Par kabhi kabhi humein strictly batana hota hai ki "yeh sirf 'ON' ya 'OFF' ho sakti hai, koi teesri cheez nahi". Yahan Literal Types kaam aate hain. Wahin dusri taraf Enums humein fixed options ko ek naam ke andar bundle karne ki facility dete hain, jaise drop-down menu ki options.

Literal Types#

Literal Types signify that the value of the variable must match the exact specified value. This is very commonly used in combination with Union (|) types.

// String Literal Union (Highly used in React for states/statuses)
type Status = "pending" | "approved" | "rejected";

let myStatus: Status = "pending"; // ✅
// myStatus = "processing"; // ❌ ERROR: Type '"processing"' is not assignable to type 'Status'.

// Number Literals exist too
type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6;
let roll: DiceRoll = 4; // ✅

Enums (Enumerations)#

Enums solve the same problem (restricting options), but TS compiles them into actual objects in the JavaScript output. They function like a bundled set of "Named Constants".

1. Numeric Enums (Default)#

By default, Enums are assigned numeric values, starting from 0.

enum Direction {
  Up,    // 0
  Down,  // 1
  Left,  // 2
  Right  // 3
}

let playerMove: Direction = Direction.Up; // Value is 0
console.log(playerMove); // 0

You can also manually assign values: enum Direction { Up = 1, Down, ... }. The subsequent values will automatically increment to 2, 3, etc.

2. String Enums#

String enums are generally safer and more readable because they display the clear string value in your debugger, rather than an obscure number.

enum UserRole {
  Admin = "ADMIN",
  Editor = "EDITOR",
  Viewer = "VIEWER"
}

const currentUserRole = UserRole.Admin;

Enums vs Union Types (The Big Debate)#

The issue with Enums: TS compiles Enums into an actual JS object/function. This slightly increases the bundle size and can sometimes behave strangely. React developers (and many modern TS developers) strongly prefer String Union Literals over Enums!

// Good (Enum style):
enum StatusEnum { Success = "SUCCESS", Error = "ERROR" }

// Better (Union Literal Style - Lighter weight):
type StatusType = "SUCCESS" | "ERROR";

Const Enums (A compromise)#

If you must use an enum, prefixing it with const stops TS from generating the compiled JS object. Instead, it injects the raw value directly into the compiled code, making it fast and lightweight.

const enum Size { Small, Medium, Large }
let mySize = Size.Medium; // In JS, this simply compiles directly to: `let mySize = 1;`