In TypeScript enum elements can also be assign to string values (instead of numeric values):
enum NumSymbol {
K = 'kilo', M = 'mega', G = 'giga'
}
console.log(NumSymbol.K);
console.log(NumSymbol.M);
console.log(NumSymbol.G)
console.log("-- looping --");
for (let key in NumSymbol) {
console.log(`key=${key}, value=${NumSymbol[key]}`);
} Outputkilo mega giga -- looping -- key=K, value=kilo key=M, value=mega key=G, value=giga
Compiled JavaScript:
var NumSymbol;
(function (NumSymbol) {
NumSymbol["K"] = "kilo";
NumSymbol["M"] = "mega";
NumSymbol["G"] = "giga";
})(NumSymbol || (NumSymbol = {}));
console.log(NumSymbol.K);
console.log(NumSymbol.M);
console.log(NumSymbol.G);
console.log("-- looping --");
for (let key in NumSymbol) {
console.log(`key=${key}, value=${NumSymbol[key]}`);
}
As opposed to numeric enums, string enums do not have reverse mapping (as seen in above example)
String enums do not have auto-increment behavior. For example following ends up in compile time error:
enum NumSymbol {
K = 'kilo', M , G
}
Outputstring-enum-exmaple2.ts(2,17): error TS1061: Enum member must have initializer. string-enum-exmaple2.ts(2,21): error TS1061: Enum member must have initializer.
Example ProjectDependencies and Technologies Used: |