Enums
A helpful addition to the standard set of datatypes from JavaScript is the enum
. An enum is a way of giving more friendly names to sets of enumerable values. It also allows us to validate a value against a set of predefined values.
TypeScript provides both numeric and string-based enums.
Numeric enums
In this example, we've defined a list of fruit in the Fruit
enum. We then create a variable named myFruit
and the user assigns a value to myFruit
by selecting one of the fruit possibilities.
The reason this works is because the enum is actually assigning a zero-based index to all of the defined values. Therefore the comparison is being made between two numeric values. In fact, if we don't want the numbers to start at zero, we can override the sequence like so:
Now our fruit indices start at 1
.
We can actually assign any numeric value, and the following items will follow incrementally:
But what if we don't want incremental values? Well, we can assign a value to each item in the list:
String enums
In a string enum, each member has to be constant-initialized with a string literal, or with another string enum member.
String enums don’t have auto-incrementing behavior. A benefit of string enums is that they will usually have a meaningful and readable value at runtime, independent of the name of the enum member itself. Whereas, numeric enums have values that may be difficult to decipher at runtime.
Consider another example:
Here we have a naïve money formatter function, formatMoney
. It takes two parameters: amount
, which is a number
, and currencySymbol
which accepts values of type CurrencySymbols
.
If we attempt to pass a currency that isn't included in the enum, we will expect an error:
Last updated