Converting strings to Enums in TypeScript
Posted: (EET/GMT+2)
TypeScript contains good support for enumeration types (enums), and I'm happy to use them whenever needed. At some point when using enums, you find yourself converting user input (strings) to TypeScript enum values.
There's an easy and good-looking solution to this, but the question is: what happens if the user supplies a string that is not part of the enum's valid values? Or, is the conversion case-sensitive or not?
Here's a little example. Let's say you have the following enum defined:
enum DateInterval {
Day,
Week,
Month,
Quarter
}
Then, you can specify a value in code with a compiler-inforced value:
var interval: DateInterval = DateInterval.Month;
console.log("Interval, step 1 = " + interval);
This outputs:
Interval, step 1 = 2
Let's add a string to enum conversion with a neat array-like indexing feature:
var value: string = "Week"; // correct casing
interval = DateInterval[value];
console.log("Interval, step 2 = " + interval);
This outputs:
Interval, step 2 = 1
Then, let's add two more input value tests:
var value: string = "weeK"; // incorrect casing
interval = DateInterval[value];
console.log("Interval, step 3 = " + interval);
var value: string = "SomethingStrange";
interval = DateInterval[value];
console.log("Interval, step 4 = " + interval);
This outputs:
Interval, step 3 = undefined Interval, step 4 = undefined
That is, unless there's a case-sensitive match to the enum value, the conversion fails, and the result is undefined. Here's the complete code and output:
enum DateInterval {
Day,
Week,
Month,
Quarter
}
var interval: DateInterval = DateInterval.Month;
console.log("Interval, step 1 = " + interval);
var value: string = "Week"; // correct casing
interval = DateInterval[value];
console.log("Interval, step 2 = " + interval);
var value: string = "weeK"; // incorrect casing
interval = DateInterval[value];
console.log("Interval, step 3 = " + interval);
var value: string = "SomethingStrange";
interval = DateInterval[value];
console.log("Interval, step 4 = " + interval);
// outputs:
Interval, step 1 = 2
Interval, step 2 = 1
Interval, step 3 = undefined
Interval, step 4 = undefined
The essential point: TypeScript automatic string-to-enum conversion works, if the string values exactly match enum values. However, if the user is able to type in or select the value, it is best to manually attempt the conversion, for example by allowing different capitalizations.
Hope this helps!