Skip to content

Notes on Enum Usage

noahdarveau-MSFT edited this page Apr 15, 2024 · 1 revision

Why use const enums?

In teams-js, we typically want to default to using const enums over regular enums whenever possible to help minimize the release package's bundle size. In typescript, const enums are a more performant version of enums, with slightly reduced functionality and some minor changes to how they are transpiled. As we use a fairly large amount of enums in teams-js, it is important to be mindful of using size optimized code options whenever possible to help keep the package from bloating over time. Even if each individual enum is quite small, all together they certainly add up to quite a bit of size.

How do const enums help reduce bundle size?

In typescript, when enums are transpiled, they are by default given reverse mapping functionality. This lets you get the left-side key by passing in a right-side value. For example:

enum Enum {
  Key,
}
let value = Enum.Key;
let nameOfValue = Enum[value]; // "Key"

When this is transpiled, there is a large amount of overhead code added to facilitate this reverse-mapping functionality, with the above code being transpiled to the following javascript:

var Enum;
(function (Enum) {
    Enum[Enum["Key"] = 0] = "Key";
})(Enum || (Enum = {}));
let value = Enum.Key;
let nameOfValue = Enum[value]; // "Key"

Unlike regular enums, const enums are completely removed at transpile time, and all of the values are inlined, which impacts a few things.

  1. The extra overhead code is not added to facilitate reverse-mapping functionality.
  2. The left-side keys can be symbolized in the minified code since the exact content value of each key is no longer needed.

Consequences of using const enums

With the space savings of using const enums, there are a few tradeoffs:

  1. The reverse-mapping functionality is eliminated, so if an enum's left-side keys need to be accessed, a const enum will not work.
  2. Since the enum is completely removed in the transpiled code, if the enum object needs to be accessed at runtime (such as through the Object.values(<enum>) method), a const enum will not work.

Which should I use?

When ultimately deciding which enum to use, the typical rule of thumb should be to use a const enum, unless any of the functionality mentioned above would prevent you from doing so.

Further Reading

For more details about enums and how they work in typescript, you can read their official documentation here