[ Guide - Enum TypeScript & JavaScript Tutorial ]

JavaScript is aware of 7 data types. Naming them: number, string, boolean, object, function, symbol and undefined. If you take it seriously, you can count null as well. Then there would be 8, but I don’t count on this one, because null isn’t callable. But what about enums? Are they inside JavaScript? No, unfortunately not. This is very sad because I have a C# background and enums are a glorious thing for counting and symbolic programming. They allow you to assign values to constant representations. It is also possible to multi assign one value to different representations. But don’t lose hope, we can achieve similarities in JavaScript and spoiler alert, Typescript got them fully implemented! Enums in JavaScript? Two alternatives Without Enums in JavaScript, the coders came up with unique solutions. We can condense all of them down to two base concepts. The first one is to define identifiers for numbers: As you can see, this method bases on an object, holding explicitly allowed values as keys and having the corresponding number saved as a value. Subsequently, you can use these values. On top of that, you can also read and assign those values, they are comparable and have underlying names. The biggest flaw in JavaScript is the fact that misspelling a property won’t raise any errors when you want to read a property’s value. During runtime, it will just return the value “undefined”. The same works the other way around, if you want to write into an object and misspell the property you want to write to it, JavaScript just appends the misspelled one as a “new” property. Anyway, this is an enormous problem. When you make such a mistake and it lastly attracts attention during runtime, you are going to have a great time debugging. Finding that little spelling mistake inside the code. The major flaw with this solution: You have no type safety inside JavaScript. Why even try to copy a construct out of a type-safe language that can’t hold its promises when implemented into JavaScript? The answer is to come up with a better solution. Therefore, I show you the second way. Use a string instead of an enum look-alike object. But working with strings can bring you drawbacks as well. What is about the overview about allowed or even possible values? This might go under when using this technique. You might think of providing a mix of the first and the second alternative to enums. We got our enum “itemCategory” set up with strings instead of numbers and can now reassign “weapon.category” with an enum representation. We kept our overview of defined possibilities of the enum. This isn’t possible when using strings. Pretty fly for an enum guy I talked in the first chapter about the possibility to double flag the values of enums. To make that, you use a trick. Define the numbers for the representations of the enum values as a basis for the power of 2. Doing it like this brings the binary combiners to the table. I advise you to design a default value for your usages. Commonly used for that is the value 0. Possibly we can double assign a value now. For example, a healing potion could also be a healing item, but also for crafting (brewing). To do so, we have to combine the corresponding values. If you stick to the second alternative, I introduced in chapter 1, then you aren’t able to double flag your properties as I did. But don’t you also think that this is still like a nifty workaround? Smart, but not as good as the original enum. We will take a look into Typescript now. This is the holy land, where milk and honey run through the rivers. Enums in TypeScript TypeScript has enums as types and you can use them easily with the keyword: “enum”. TypeScript behaves here like C# and starts counting with 0. If you don’t want this, just assign the first enumeration with your favorite number. When numbers aren’t a meaningful representation, then you can also rely on strings as well. Note: The language allows you to mix up strings and numbers as assignments inside the same enum. But the practicability isn’t quite good on this one. Better stick to one type of assignment per enumeration. You can realize the combination of enum values in typescript as well. Make sure to have a default value (0). Convert it back to JavaScript? Although you don’t have to think or code in JavaScript code anymore when using TypeScript, the browser has too. Therefore, TypeScript will be converted back into JavaScript and this is a tensioning part, to look at how it is being done! Taking this example: Compile your code back to JavaScript and this is the output: We take a deep look into this humongous beast step by step. The first act is the creation of an object called itemCategory in line 1. This will have the value undefined. It will be passed to a function in the next step. Inside the body of this function, you see four assignments corresponding to our known enum representations “ healing ”, ” crafting ”, “ armor ”, “ weapon ”. But what is that in front of the equal sign? Let's look at the 2nd line in detail. We observe that this is a creation of the property inside the whole construct. The itemCategory[“crafting”] appends to the newly created object itemCategory (line1 of X10_ConvertedTsEnumIntoJS.js) the property crafting and sets it with itemCategory[“crafting”]=1 to 1. Note: In JavaScript, an assignment will always return the assigned value. Here, the assigned value of 1 is also the returned value of this assignment. Because of the returning value of an assignment, the code is instantly creating another property with the name of “1“. This property will get the value “crafting”. If you inspect the line precisely, you will come to the conclusion that this is a dual-assignment. We get the property 1 assigned with “crafting” and get the property “crafting” with the value “1”. There are now two ways to identify the same representation for “crafting”:”1" and “1”:”crafting”. The compiled code results in an object creation like: This is helpful for displaying the values behind the enum. This example states Typescript isn’t doing things differently here. How should it be? It has to be converted back into JavaScript. What Typescript does, it makes our lives as a programmer better and safer. Typesafe! It introduces us to a less error-prone language where we can focus on the task to produce and create instead of a walk through a gauntlet, hoping for the best, try to avoid every pitfall JavaScript prepared for us. A thing to mention here: const can be used also, then you entering the strict mode for the JavaScript compilation. You are losing one of the two ways to comprehend the enum representation. You aren’t able to get to the name for the value. This option is gone. It becomes clear when we look into the compiled code. We got out enum in Typescript here. And compiled it back to JavaScript. There is none expect: “use strict”. The enum vanished entirely. Where is it gone? We make an assignment from our enum: An inspect the compilation another time: Like I mentioned, the two directions to get the name by the value and to get the value by the name are gone. It leaves only one of them. The number. Are there other ways? Yep, you can use a so-called “Discriminated Union”. This is just a variable of type “type” holding one of many values. Because of not writing the enum type anytime, we can see this as a lightweight alternative. Because JavaScript works with strings, and this “Discriminated Union” also, you are coding then more likely to JavaScript. It is like the classical way of working with strings, restricted to a few allowed ones. You can do it without the enum construct, while just relying on “type”, but if you want to use numbers, then you have to make a manual conversion back to the underlying constant representation. This work, an enum offers you as already done. Conclusion Whatever you want to take, keep aligned for your entire project. Doing mixed usages inside one project will only lead to confusion and constant rethinking. Bugs are also minimized by staying only to one way of doing. To find the right thing for your needs, you have to weigh up the pros and cons of the introduced methods, like always in life!