It's important to note that enum
usage in TypeScript can be a bit tricky, as they are often misunderstood and can be used either as string-based or numeric-based types.
If you utilize your enum
like this:
State.OnShoppingListUnchecked
It will be treated as a number and compared to the numeric value of 1. However, consider the following nested enum code:
a === State['OnShoppingListUnchecked'] // compare to 1
a === State[State['OnShoppingListUnchecked']] // compare to 'OnShoppingListUnchecked' string
a === State[State[State['OnShoppingListUnchecked']]] // Once again against numeric 1
// ... and so on
If you are receiving a string from the server instead of a number, your comparisons may fail. You can automate this check by doing the following:
let toCompare = 1 // Value to compare against
if (typeof(compareValue) === 'number') {
return State[toCompare] === compareValue // Compare number to number
} else if (typeof(compareValue) === 'string') {
return State[State[toCompare]] === compareValue // Compare input string to string representation of enum
}
This ensures that regardless of whether the input is a string or number, you are comparing it against the correct enum
entry.
String-based enums have been supported since TypeScript 2.4 and above, but in my opinion, their usage should be limited. Number-based enums provide an easy way to access additional information from array-like structures, which is not possible with string-based enums:
enum NamesEnum {
NAME0 = 0,
NAME1 = 1
};
namesToDisplay: string[] = [
'Name1 display value',
'Name2 display value'
];
let enumVal = someFunctionThatGetsEnum(); // Only works for number-based enums
this.currentDisplay = this.namesToDisplay[enumVal];
In the template:
<p>{{ currentDisplay }} </p>
If you don't need to index arrays using enums, you can replace string-based enums with String Literal Types, which offer similar benefits without as much concern for type and compatibility issues.