’Enums’ in TypeScript is a feature that allows you to define a named set of constant values, typically to represent a collection of related items or categories. Enums can make your code more understandable and less error-prone by providing a way to use symbolic names rather than raw values, such as integers or strings, directly.
There are two main types of enums in TypeScript: numeric enums and string enums.
1. Numeric enums:
By default, numeric enums will have their members’ values auto-incremented from 0. You can also explicitly set the initial value or assign specific values to each member.
Example:
enum DaysOfWeek {
Sunday, // 0
Monday, // 1
Tuesday, // 2
Wednesday, // 3
Thursday, // 4
Friday, // 5
Saturday // 6
}
Usage:
const today: DaysOfWeek = DaysOfWeek.Friday;
console.log(today); // 5
2. String enums:
These Enums allow you to use string values instead of numeric values.
Example:
enum Directions {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT"
}
Usage:
const move: Directions = Directions.Left;
console.log(move); // "LEFT"
Enums in TypeScript are a feature that allows you to define a named set of constant values, typically to represent a collection of related items or categories. Enums can make your code more understandable and less error-prone by providing a way to use symbolic names rather than raw values, such as integers or strings, directly.
There are two main types of enums in TypeScript: numeric enums and string enums.
1. Numeric enums:
By default, numeric enums will have their members’ values auto-incremented from 0. You can also explicitly set the initial value or assign specific values to each member.
Example:
enum DaysOfWeek {
Sunday, // 0
Monday, // 1
Tuesday, // 2
Wednesday, // 3
Thursday, // 4
Friday, // 5
Saturday // 6
}
Usage:
const today: DaysOfWeek = DaysOfWeek.Friday;
console.log(today); // 5
2. String enums:
These enums allow you to use string values instead of numeric values.
Example:
enum Directions {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT"
}
Usage:
const move: Directions = Directions.Left;
console.log(move); // "LEFT"