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
}
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.
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.
Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums.
There are three types of TypeScript enums, namely: Numeric enums. String enums. Heterogeneous enums.
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With