Enums are similar to JavaScript objects, but they have some special attributes that help in the development of your application. You can have a friendly name for numeric values or a more controlled environment for the constants on the variables a function can accept.
A numeric enum can be created without any declaration. By doing this, it will start with the initial values of 0 and finish with the value of the final index number; or, you can get the name of the enum, passing the index of the enum value:
enum ErrorLevel {
Info,
Debug,
Warning,
Error,
Critical,
}
console.log(ErrorLevel.Error); // 3
console.log(ErrorLevel[3]); // Error
Or, an enum can be declared with values. It can be an initial declaration that the TypeScript compiler will interpret the rest of the elements as an increment of the first one, or an individual declaration:
enum Color {
Red = '#FF0000',
Blue = '#0000FF',
Green = '#00FF00',
}
enum Languages {
JavaScript = 1,
PHP,
Python,
Java = 10,
Ruby,
Rust,
TypeScript,
}
console.log(Color.Red) // '#FF0000'
console.log(Languages.TypeScript) // 13