Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the TypeScript transpiler compile enums into dictionary lookups instead of simple objects?

I am curious as to why the TypeScript transpiler compiles enums into dictionary lookups instead of simple objects. Here is an example TypeScript enum:

enum transactionTypesEnum {
    None = 0,

    OSI = 4, 
    RSP = 5,
    VSP = 6,
    SDIV = 7,
    CDIV = 8
}

Here is the JS code TypeScript emits:

var TransactionTypes;
(function (TransactionTypes) {
    TransactionTypes[TransactionTypes["None"] = 0] = "None";
    TransactionTypes[TransactionTypes["OSI"] = 4] = "OSI"; 
    TransactionTypes[TransactionTypes["RSP"] = 5] = "RSP"; 
    TransactionTypes[TransactionTypes["VSP"] = 6] = "VSP"; 
    TransactionTypes[TransactionTypes["SDIV"] = 7] = "SDIV";
    TransactionTypes[TransactionTypes["CDIV"] = 8] = "CDIV";
})(TransactionTypes || (TransactionTypes = {}));

My curiosity is wondering why TypeScript doesn't simply do this:

var TransactionTypes = {
    None: 0,
    OSI: 4,
    RSP: 5,
    VSP: 6,
    SDIV: 7,
    CDIV: 8
}
like image 453
Icemanind Avatar asked Oct 22 '18 12:10

Icemanind


People also ask

Why are enums bad in TypeScript?

The they are useless at runtime argument and agree, if at runtime some code tries to change the values of one of your enums, that would not throw an error and your app could start behaving unexpectedly ( that is why Object.

How does ENUM work in TypeScript?

In TypeScript, enums, or enumerated types, are data structures of constant length that hold a set of constant values. Each of these constant values is known as a member of the enum. Enums are useful when setting properties or values that can only be a certain number of possible values.

Should enums be used in TypeScript?

Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums.

Does TypeScript support heterogeneous enum?

There are three types of TypeScript enums, namely: Numeric enums. String enums. Heterogeneous enums.


1 Answers

TypeScript enum types provide a safe two-way mapping, so you can get the name or the value based on all of the following (example getting the value, the name from the value, and the value from a plain string)

enum Musketeers {
  CAV = 0,
  BAS = 1,
  USR = 2
}

const selection = Musketeers.BAS;

// 1
console.log(selection);

const selectionName = Musketeers[selection];

// BAS
console.log(selectionName);

const fromString = Musketeers['BAS'];

// 1
console.log(fromString);

In particular, this line is not supported by the dictionary (without writing additional code):

// Gets the name from the value
const selectionName = Musketeers[1];
like image 77
Fenton Avatar answered Oct 23 '22 04:10

Fenton