What Are String Enums in TypeScript?

Introduced in TypeScript v2.4, string enums make it possible to define a set of named constants that can be initialized to the following values:

  1. A literal string value, or;
  2. Another string enum member.

String enums can be particularly useful for:

  • Improving code maintainability, readability, consistency, and type safety;
  • Serialization over transfer protocols;
  • Debugging;
  • etc.

For example, the following creates a string enum of grocery items, where each enum member is initialized to a string literal:

// TypeScript 2.4+
enum Grocery {
  Cereal = "cereal",
  Fish = "fish",
}

A string enum member can also be initialized to another string enum member, as you can see in the following example:

// TypeScript 2.4+
enum Grocery {
  Cereal = "cereal",
  Fish = "fish",
  Musli = Cereal,
  Tuna = Fish,
}

This would compile into the following JavaScript code:

var Grocery;
(function (Grocery) {
  Grocery["Cereal"] = "cereal";
  Grocery["Fish"] = "fish";
  Grocery["Musli"] = "cereal";
  Grocery["Tuna"] = "fish";
})(Grocery || (Grocery = {}));

As you can see, string enums are compiled into a JavaScript object that only stores forward mappings — which means that you can get the string enum value using a member name, but you cannot do the inverse:

// allowed: forward mapping (name -> value)
Grocery["Fish"]

// not allowed: reverse-mapping (value -> name)
Grocery["fish"]

Since string enums compile into a JavaScript object, it means that you can use them in your code as values, for example, like so:

// ...
const shoppingCart = [
  Grocery.Tuna,
  Grocery.Musli,
];

console.log(shoppingCart); // ['fish', 'cereal']

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.