Background:
Enum is a type that originated from C/C++ and other languages to describe finite sets of named constants. They did not exist in JavaScript, but support has been implemented in TypeScript. To improve performance, const enum was introduced — an extension where values are directly substituted at compile time, rather than being full-fledged objects.
Problem:
Regular enums generate a significant amount of auxiliary code in JS (objects providing a bidirectional mapping of name<->value). This is not always necessary, especially when maximum performance and minimal bundle size are prioritized.
Solution:
Use const enum when you need to inline values at compile time and avoid unnecessary code. However, const enums have limitations — they only work within a TypeScript project, are hard to use when transpiling to different modules, and may have issues with tree shaking and import/export.
Example code:
const enum Direction { Up, Down, Left, Right } const move = Direction.Left; // In JS, this will become simply 2
Key features:
Can const enums be used in d.ts files and public libraries?
No. It is recommended to avoid const enums in libraries, as they are inlined only during compilation, which often causes errors during rebuilds and type definitions.
What will happen when using const enums with the isolatedModules parameter or when compiling with babel?
An error will occur: babel and isolatedModules do not support inlining const enums, as they cannot guarantee safe substitution of values at the compilation stage of a single file.
Can computed values and string values be used in const enums?
Complex calculations (such as expressions through functions or variables) are prohibited. Only simple numbers and strings are allowed.
A const enum was published in a library, described in .d.ts, and the consumer received an error due to the absence of an import string in the final bundle.
Pros:
Cons:
Used const enum only within private parts of the project, not exporting it outward:
const enum Color { Red, Green, Blue } let arr = [Color.Red, Color.Green];
Pros:
Cons: