🌱BeginnerTypeScript Basics
Enums
Numeric enums, string enums, const enums, and when to use union types instead.
Overview
Enums (enumerations) define a set of named constants. Instead of scattering magic strings or numbers throughout your code, you give them meaningful names grouped in one place.
TypeScript has two main enum flavours:
- **Numeric enums** members are automatically assigned integers (0, 1, 2, …) or manually assigned numbers
- **String enums** members have explicit string values; safer and more readable in logs and APIs
**`const enum`** is optimised: the compiler inlines the values directly (no runtime object is generated), resulting in smaller output.
However, many TypeScript teams now prefer **union types with literal strings** over enums: `type Status = "active" | "inactive" | "pending"`. They are simpler (no special syntax), work seamlessly with JSON, and are easier to understand for newcomers. Both patterns are valid use whichever your team prefers.
Key Points
- •Numeric enum: `enum Direction { North, South, East, West }` starts at 0 by default
- •String enum: `enum Color { Red = "RED", Green = "GREEN" }` explicit string values
- •`const enum` inlines values at compile time no runtime object generated
- •Enum members are accessed like: `Direction.North`, `Color.Red`
- •Numeric enums allow reverse mapping: `Direction[0]` → `"North"`; string enums do not
- •Union literal alternative: `type Status = "open" | "closed" | "pending"` often preferred
- •Use string enums (or union literals) when values appear in logs, APIs, or persisted data
Examples
Numeric and string enums
// Numeric enum (auto-increments from 0)
enum Direction {
North, // 0
South, // 1
East, // 2
West, // 3
}
console.log(Direction.North); // 0
console.log(Direction[0]); // "North" (reverse mapping)
// Custom start value
enum Priority {
Low = 1,
Medium, // 2
High, // 3
Critical = 100,
}
// String enum
enum Status {
Active = "ACTIVE",
Inactive = "INACTIVE",
Pending = "PENDING",
}
console.log(Status.Active); // "ACTIVE"
// String enums have NO reverse mapping
console.log(Status["ACTIVE"]); // undefinedUsing enums in functions
enum LogLevel {
Debug = 0,
Info = 1,
Warn = 2,
Error = 3,
}
function log(level: LogLevel, message: string): void {
const prefix = LogLevel[level]; // reverse mapping
console.log(`[${prefix}] ${message}`);
}
log(LogLevel.Info, "Server started"); // [Info] Server started
log(LogLevel.Error, "DB connection failed"); // [Error] DB connection failed
// TypeScript prevents passing arbitrary numbers to enum params
// log(99, "test"); // Works at runtime but enum doesn't cover 99const enum vs union type a comparison
// const enum inlined at compile time
const enum HttpMethod {
GET = "GET",
POST = "POST",
PUT = "PUT",
DELETE = "DELETE",
}
function request(method: HttpMethod, url: string) {
console.log(`${method} ${url}`);
}
request(HttpMethod.GET, "/api/users");
// Compiled output: request("GET", "/api/users") enum is gone
// Union literal often simpler, no special runtime behavior
type HttpMethodAlt = "GET" | "POST" | "PUT" | "DELETE";
function requestAlt(method: HttpMethodAlt, url: string) {
console.log(`${method} ${url}`);
}
requestAlt("GET", "/api/users");
// requestAlt("PATCH", "/x"); // Error!Common Mistakes
- Using numeric enums in APIs or databases the numbers are meaningless outside TypeScript; use string enums or literal types for persisted/transmitted values
- Forgetting that `const enum` cannot be used from external modules (it is inlined; there's no runtime object) use regular enums for library exports
- Mixing enum values with raw numbers `if (status === 1)` instead of `if (status === Status.Active)` defeats the purpose
Note
For most projects, prefer union literal types (`type Status = "open" | "closed"`) over enums. They're simpler, work naturally with JSON serialisation, and don't require learning TypeScript-specific syntax. Use enums when you specifically need reverse mapping or are working in a codebase that already uses them.
Exercises
Write TypeScript code to solve each exercise. Click Run to compile and execute it right here, then mark as done.
Loading editor…
Completed: 0 / 5 exercises
Knowledge Check
Question 1 of 4