Numeric enums let you group related numbers with names. This makes your code easier to read and understand.
0
0
Numeric enums in Typescript
Introduction
When you want to name a set of related numbers, like days of the week or directions.
When you need to compare or switch between fixed numeric values with meaningful names.
When you want to avoid using 'magic numbers' directly in your code.
When you want to make your code clearer for others by using descriptive names instead of numbers.
Syntax
Typescript
enum Name {
Member1 = 1,
Member2,
Member3 = 10,
Member4
}If you don't assign a number to the first member, it starts at 0 by default.
Members without assigned numbers get the previous member's number plus one.
Examples
Starts at 1 for Up, then Down is 2, Left is 3, Right is 4 automatically.
Typescript
enum Direction {
Up = 1,
Down,
Left,
Right
}No numbers assigned, so Ready=0, Waiting=1, Done=2 by default.
Typescript
enum Status {
Ready,
Waiting,
Done
}Red is 5, Green is 10, Blue is 11 (one more than Green).
Typescript
enum Color {
Red = 5,
Green = 10,
Blue
}Sample Program
This program defines days Monday to Friday starting at 1. It checks if a day is weekend (6 or 7). Monday prints as 1, Wednesday as 3, and Monday is not weekend.
Typescript
enum Weekday {
Monday = 1,
Tuesday,
Wednesday,
Thursday,
Friday
}
function isWeekend(day: Weekday): boolean {
return day === 6 || day === 7;
}
console.log(Weekday.Monday); // 1
console.log(Weekday.Wednesday); // 3
console.log(isWeekend(Weekday.Monday)); // falseOutputSuccess
Important Notes
Numeric enums can be used in comparisons and switch statements easily.
You can get the name from the number using reverse lookup, like Weekday[1] gives 'Monday'.
Be careful to assign numbers if you want specific values; otherwise, they auto-increment.
Summary
Numeric enums give names to numbers for clearer code.
Members auto-increment if no number is assigned.
Use enums to avoid magic numbers and improve readability.