Skip to content Skip to sidebar Skip to footer

Why Does TypeScript Use Object Property Assignments As Object Keys And Variable Assignments As Function Arguments?

In the accepted answer for a question titled 'Compile an enum in TypeScript', the following TypeScript: enum Fruit {APPLE, ORANGE}; Is shown to compile to this JavaScript: var Fru

Solution 1:

The evaluation of an assignation is the value. The purpose of the IIFE function is to create an object that works both ways value -> key and key -> value.

An interesting console.log here is Fruit itself.


var Fruit;

(function (Fruit) {
    Fruit[Fruit["APPLE"] = 50] = "APPLE";
    Fruit[Fruit["ORANGE"] = 10] = "ORANGE";
})(Fruit || (Fruit = {}));

// main.js
var bowl = [Fruit.APPLE, Fruit.ORANGE];
console.log(Fruit);


If we start over the whole explanation :

Fruit is passed to the IIFE function, if it doesn't exist, it's initialized as an empty object {}.

Then the first couple key -> value is inserted into the object, that will result as :

{
  APPLE: 50,
}

(Because the assignation is executed first on the line) :

Fruit[Fruit["APPLE"] = 50] = "APPLE";

Then the second couple is inserted into Fruit object :

Fruit[50] = "APPLE";

Solution 2:

The expression Fruit["APPLE"] = 0 evaluates to 0, or the value of the key assignment. Which means that in addition to assigning

Fruit["APPLE"] = 0

we are also doing this assignment

Fruit[0] = "APPLE"

which makes it so that you can both get the string name of the enum by its number value and the number value by its string name.


Solution 3:

Fruit[Fruit["APPLE"] = 0] doesn't mean to be Fruit.APPLE:

Fruit["APPLE"] = 0 So, it is Fruit[0]. Now, Fruit[0] = "APPLE".

Thus, you'll have:

Fruit[0] = "APPLE"
Fruit[1] = "ORANGE"

But not:

Fruit.APPLE = "APPLE"
Fruit.ORANGE = "ORANGE"

So, wrapping them inside IIFE:

(function (Fruit) {
  // here, Fruit is {}
})(Fruit || (Fruit = {}))

And when using:

Fruit[0] = "APPLE"

Will eventually become:

Fruit = { 0: "APPLE", 1: "ORANGE" }

Hence, your example will be invalid.


Post a Comment for "Why Does TypeScript Use Object Property Assignments As Object Keys And Variable Assignments As Function Arguments?"