Library Authorship Considerations
You'll learn: Why library authors often prefer string-literal unions over enums to avoid exposing runtime objects and achieve better tree-shaking.
When you publish a TypeScript library, you're not just writing code for yourself—you're creating an API that others will consume. This changes how you should think about enums.
The Bundle Size Problem
Enums generate JavaScript code at runtime. When someone imports a single function from your library, they might accidentally pull in enum definitions they never use. Unlike string-literal unions (which exist only at compile time), enums are real objects that bundlers must include.
// Your library code
export enum Status {
Pending = "PENDING",
Active = "ACTIVE",
Completed = "COMPLETED"
}
export function createTask(status: Status) { ... }
Even if a consumer only wants Status.Pending, the entire Status object gets bundled—all three members. Modern tree-shaking can't eliminate unused enum members because enums are runtime values.
The Union Alternative
Library authors increasingly choose string-literal unions instead:
// Compile-time only, zero runtime cost
export type Status = "PENDING" | "ACTIVE" | "COMPLETED";
export function createTask(status: Status) { ... }
This approach gives consumers the same autocomplete and type safety, but produces zero JavaScript. The bundle only includes what's actually used.
The API Surface Trade-off
Enums expose an object your consumers can iterate over or reference. Unions don't—they're purely type-level. For libraries, this is often desirable: you maintain full control over the API without leaking implementation details.
Key Takeaway: Library authors prefer string-literal unions to enums because they eliminate runtime overhead, enable better tree-shaking, and keep the public API purely type-based without exposing enumerable objects.