Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enums in TypeScript: what is the JavaScript code doing?

Tags:

People also ask

How does enum work in TypeScript?

Enums are one of the few features TypeScript has which is not a type-level extension of JavaScript. Enums allow a developer to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums.

Can enum be used in JavaScript?

Enums are not supported in JavaScript natively. We can however create Enums using Object. freeze by creating objects containing all the enumerable properties and then freezing the object so that no new enum can be added to it.

Is A TypeScript enum an object?

As the TypeScript documentation says, even though enums are real objects that exist at runtime, the keyof keyword works differently than you might expect for typical objects. Instead, using keyof typeof will get you a type that represents all enum keys as strings, as we have seen above.

Should enums be used in TypeScript?

Enums are just one useful way to organize code in TypeScript. Here are some reasons why enums come in handy: With enums, you can create constants that you can easily relate to, making constants more legible. Developers have the freedom to create memory-efficient custom constants in JavaScript.


The following TypeScript:

enum PrimaryColors { Red, Green, Blue };

Produces the following JavaScript:

var PrimaryColors;
(function (PrimaryColors) {
    PrimaryColors[PrimaryColors["Red"] = 0] = "Red";
    PrimaryColors[PrimaryColors["Green"] = 1] = "Green";
    PrimaryColors[PrimaryColors["Blue"] = 2] = "Blue";
})(PrimaryColors || (PrimaryColors = {}));
;

I am embarrassed to admit that I don't understand what the JavaScript is doing.
The function in parentheses is assigning string values using another assignment as the index/key. I have not seen anything like this before.
And what is the purpose of the (PrimaryColors || (PrimaryColors = {}) following the function?
If the answer is to learn JavaScript properly, I will readily accept it, provided it comes with a suggested source that clearly explains what I am seeing here.