Learn Programming, Tech & Coding · Free Online Tools

IT Question Answer
Back to TypeScript
TypeScript Enums and When to Use Them

TypeScript Enums and When to Use Them

TypeScript2,602 viewsBy Admin
typescriptenumswhenthem

What are Enums?

Enums let you define a set of named constants, making code more readable and intent clearer than magic strings or numbers.

Numeric Enums

enum Direction { Up, Down, Left, Right }
let move: Direction = Direction.Up; // 0

String Enums (Preferred)

enum Status {
  Active = "ACTIVE",
  Inactive = "INACTIVE",
  Banned = "BANNED",
}
const s: Status = Status.Active; // "ACTIVE"

Enums vs Union Types

// Often a union is simpler and lighter:
type Status = "active" | "inactive" | "banned";
EnumUnion
Runtime codeYesNo (erased)
ReadabilityGoodGood

FAQs

Enum or union type?

Prefer union types unless you need a runtime object. More in our TypeScript guides.

What is a const enum?

An enum inlined at compile time for zero runtime cost.