TypeScript Enumerables
In Java, enumerables or enums for short, are a special type of class that represents a group of related constants. For example a list of the days of the week or a set of Redux action types are good candidates for a enumerable. These can come in handy when your code references these group of constants but you want a single source of truth. In addition, enums improve readability via documenting the intent of your code. Vanilla JavaScript does not have enums but they are available in the superset of JavaScript, TypeScript version 2.4 and on. There are three types of enums in Typescript: numeric, string, and heterogenous.
Numeric Enumerables
The default behavior of Typescript enums is to be numeric based. That is that enum strings are stored as numbers. It is noted that the string can contain numbers. The number each string is stored as can be specified or will auto increment based on the previous value or start at zero if no value is specified. For example, in Figure 1 the two enumerables are defined with the keyword enum
followed by the name in Pascal Case.
Due to the auto incrementing of enums the string values of FanSpeed0
and FanSpeed1
are equivalent. Note that it is convention to specify the strings in Pascal Case as well. It is not required by TypeScript that all the values be different but it is highly recommended for clarity purposes.
String Enumerables
The only difference from numerical to string enumerables is that the values are stored as strings. String values can help provide clarity to your enums and help during debugging via error reporting with meaningful string values.
Heterogenous Enumerables
Finally, heterogenous enumerables simply contain a mix of numerics and strings as seen in Figure 3. Although this can be done, I am not sure what the use case would be as the intent of an enum is to be a group of closely related strings/values.
Usage
An enumerables value can be accessed similar to an object using either dot notation or bracket notation. The strings can be accessed via bracket notation of the value
Additional Information
In the figures 1 through 3, all enumerables values are constants but the values can reference a function to be calculated. It is recommended for clarity and a small performance boost that the enums values are constants. If the values of the enum strings are expected to change a enumerable is likely not the correct data structure.
For additional information on TypeScript enumerables see the official documentation: