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

Viewed 124

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
}
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];
Related