#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
4 min read
Question 10 of 48easy

What are Enums in TypeScript?

Named constants with enums.

What You'll Learn

  • Numeric enums
  • String enums
  • const enums

Numeric Enums

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

let dir: Direction = Direction.Up;
console.log(dir); // 0

// Custom values
enum Status {
  Pending = 1,
  Active = 2,
  Inactive = 3
}

String Enums

code.tsTypeScript
enum Color {
  Red = "RED",
  Green = "GREEN",
  Blue = "BLUE"
}

console.log(Color.Red); // "RED"

const Enums

code.tsTypeScript
// Inlined at compile time (no runtime object)
const enum Size {
  Small = "S",
  Medium = "M",
  Large = "L"
}

let size = Size.Small;
// Compiles to: let size = "S";

Alternative: Union Types

code.tsTypeScript
// Often preferred over enums
type Status = "pending" | "active" | "inactive";

function setStatus(status: Status) {
  // ...
}