Close

TypeScript - String Enums

[Last Updated: Oct 13, 2018]

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]}`);
}

Output

kilo
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
}

Output

string-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 Project

Dependencies and Technologies Used:

  • TypeScript 3.1.1
TypeString - String Enums Select All Download
  • typescript-string-enums
    • string-enum-exmaple.ts

    See Also