With the number of developers we employ and the level of complexity of our projects, it is sometimes hard for people to remember all the constants and defaults for every object. We generally build Typescript Interfaces that assist in this, but sometimes we need more than just definitions, but actual hard data included. Enum to the rescue…. sort of.
Enum, as many of you know, is a way to store constants in a nice clean object that intellisense remembers and prompts for. They can be a lifesaver, but as all our C# developers will tell is, they are numeric.
Typescript, however, is actually just a transpiler. It converts what it sees into javascript. In Javascript, there is no such thing as an “enum”. Here’s how it is compiled.
Suppose we have this
enum Color { Green, Red, Blue }
In Javascript, it turns into this:
{ 0: "Green" 1: "Red" 2: "Blue" "Blue": 2 "Green": 0 "Red": 1 }
And that…. is useless if you want to force an interface to require the user to have specific data in a field rather than just including the Type. If it was numeric, it works, string… nope.
Luckily, there’s a great work-around. We lie to Typescript.
enum Color { Green ="Green", Red = "Red", Blue = "Blue" }
We tell Typescript that the value there is “probably” a number, so we don’t get an error. And the Typescript converts this to the following in JS:
var Color; (function(Color) { Color[Color["Green"] = "Green"] = "Green"; Color[Color["Red"] = "Red"] = "Red"; Color[Color["Blue"] = "Blue"] = "Blue"; })(Color || (Color = {}));
which means, we’ll get an object like this:
{ "Green": "Green" "Red": "Red" "Blue": "Blue" }
And that means that our intelliesense for “Color” will offer us the actual names of the colors and the result will be the string value. For us, we do a lot of integration where the server requires specific name/value combinations to update. SalesForce, for example, has a set of named fields and we need to send them a value. So, we can use and Enum of salesforce field names:
enum SalesForceContactFields { contactId:"contactID", firstName: "firstName", lastName: "lastName" } interface ISalesForceContact{ value: string; name: SalesForceContactFields; }
Now, when we build an object to send to SalesForce, we can be certain that all the names are acceptable, no misspellings, no names that are incorrect or don’t exist, etc… and Typescript does the validation for all of us.
I discovered this here:
http://stackoverflow.com/questions/33629456/typescript-angularjs-1-how-to-connect-enum-with-select-directive/37444513#37444513
and then also here:
https://blog.rsuter.com/how-to-implement-an-enum-with-string-values-in-typescript/
Now, there ARE other ways to accomplish a similar feature for using these string values in general code, but they DO NOT work as Types in interfaces. – At least not in my experience so far 🙂
[disqus]