Enums
Numeric enums, string enums, const enums, and when to prefer union types instead
Skills taught: ts.numeric-enum, ts.string-enum, ts.const-enum, ts.enum-vs-union
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 lookup)
// Custom numeric start
enum Priority {
Low = 1,
Medium = 5,
High = 10
}
console.log(Priority.High); // 10
// String enum — values are explicit readable strings
enum Status {
Active = 'ACTIVE',
Inactive = 'INACTIVE',
Pending = 'PENDING'
}
console.log(Status.Active); // 'ACTIVE'
console.log(Status.Inactive); // 'INACTIVE'
function processOrder(status: Status): string {
switch (status) {
case Status.Active: return 'Processing...';
case Status.Inactive: return 'Account inactive';
case Status.Pending: return 'Waiting for payment';
}
}
console.log(processOrder(Status.Active));
console.log(processOrder(Status.Pending));
const enums and the union type alternative
// const enum — inlined at compile time, no runtime object
const enum Size { Small = 'S', Medium = 'M', Large = 'L' }
const mySize = Size.Medium; // compiled to: const mySize = 'M'
// Size doesn't exist at runtime — it's replaced by its value
// Union type alternative — often preferred in modern TS
type Direction = 'N' | 'S' | 'E' | 'W';
function move(dir: Direction, steps: number): string {
return `Moving ${steps} step(s) ${dir}`;
}
console.log(move('N', 3));
// move('X', 3); // Error: 'X' is not assignable to Direction
// Object + keyof pattern — no enum, same type safety
const Status = {
Active: 'ACTIVE',
Inactive: 'INACTIVE',
Pending: 'PENDING'
} as const;
type StatusType = typeof Status[keyof typeof Status];
// same as: 'ACTIVE' | 'INACTIVE' | 'PENDING'
function setStatus(s: StatusType): void {
console.log('Status set to:', s);
}
setStatus(Status.Active); // 'ACTIVE'
setStatus('PENDING'); // also works — literal is valid
// setStatus('UNKNOWN'); // Error
console.log(Status);
Frequently Asked Questions
Should I use enums or union types?
Union types ('active' | 'inactive') are simpler, have no runtime overhead, and are just plain JS. Use them for most cases. Use enums when: the group of constants needs an explicit name (Status, Direction), when you want autocomplete to show just the enum members, or when the values need to be iterable at runtime (Object.values(MyEnum)). The 'as const object' pattern is a middle ground: const Status = { Active: 'ACTIVE' } as const — typed like an enum, plain JS at runtime.