TS Enums
An enum is a named set of constants. TypeScript has two flavours — numeric and string. Modern style: prefer string enums or union-of-literal types.
Numeric enum (the original)
TS
enum Direction {
Up, // 0
Down, // 1
Left, // 2
Right, // 3
}
const d: Direction = Direction.Up;
console.log(d); // 0
String enum (recommended)
TS
enum Status {
Paid = 'paid',
Pending = 'pending',
Refunded = 'refunded',
}
const s: Status = Status.Paid;
console.log(s); // 'paid'
console.log(Object.values(Status)); // ['paid', 'pending', 'refunded']
const enum — erased at compile
TS
const enum Direction {
Up = 'up',
Down = 'down',
}
const d = Direction.Up;
// Compiles to: const d = 'up'; — no runtime object
Faster and smaller, but conflicts with isolated modules and Babel — many teams disable them.
Modern alternative — union of literals
TS
type Status = 'paid' | 'pending' | 'refunded';
function describe(s: Status): string {
switch (s) {
case 'paid': return 'OK';
case 'pending': return 'Awaiting';
case 'refunded': return 'Refund issued';
}
}
Or — as const arrays
TS
const STATUSES = ['paid', 'pending', 'refunded'] as const; type Status = typeof STATUSES[number]; // 'paid' | 'pending' | 'refunded'
You can iterate at runtime and still get the union type at compile time.
Tip: For new code, union-of-literals or
as const arrays usually beat enums — they're erased like other type info, integrate better with JSON / APIs, and don't suffer enum quirks.Example
Example
enum Status {
Paid = 'paid',
Pending = 'pending',
Refunded = 'refunded',
}
const s: Status = Status.Paid;
console.log(s, Object.values(Status));
Try it Yourself »
Exercise
Keyword that declares an enum.
Status { Paid = 'paid' }
Four letters.
Discussion
Loading…