What You'll Learn
You'll learn how the preserveConstEnums tsconfig flag changes how TypeScript compiles const enums, keeping them as runtime objects instead of inlining their values.
The Default Behavior Recap
Normally, const enum values are completely inlined at compile time—they vanish from your compiled JavaScript, replaced directly with their literal values. This makes your bundle smaller and faster, but it also means the enum object doesn't exist at runtime.
What preserveConstEnums Does
The preserveConstEnums flag tells TypeScript: "Inline the values like normal, but ALSO emit the enum as a regular object in the output."
Think of it like getting the best of both worlds—or at least trying to. You get the performance of inlining, but you also get the runtime object if you need it for reflection, debugging, or compatibility with tools that expect enums to exist.
When This Matters
This flag becomes important when:
- You're publishing a library and consumers might need the enum object
- You use debugging tools that inspect enum objects at runtime
- You have code that iterates over enum members or uses reverse mapping patterns
- You need compatibility with the
isolatedModulesflag (which we covered earlier)
The Trade-off
With preserveConstEnums enabled, your bundle size increases slightly because the enum object is included in the output—even though TypeScript still inlines the values wherever you use them. You're trading file size for compatibility and runtime availability.
Key Takeaway:
The preserveConstEnums flag emits const enums as regular runtime objects while still inlining their values, giving you compatibility at the cost of a slightly larger bundle.