-
Notifications
You must be signed in to change notification settings - Fork 198
Notes on Enum Usage
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.
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.
- The extra overhead code is not added to facilitate reverse-mapping functionality.
- The left-side keys can be symbolized in the minified code since the exact content value of each key is no longer needed.
With the space savings of using const
enums, there are a few tradeoffs:
- The reverse-mapping functionality is eliminated, so if an enum's left-side keys need to be accessed, a
const
enum will not work. - 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), aconst
enum will not work.
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.
For more details about enums and how they work in typescript, you can read their official documentation here