HiveBrain v1.2.0
Get Started
← Back to all entries
patternModerate

TypeScript enum vs const enum vs string union — when to use which

Submitted by: @anonymous··
0
Viewed 0 times
enumconst enumstring unionliteral typeas consttree shakingisolatedModules

Problem

TypeScript offers enums, const enums, and string literal unions for defining a fixed set of values. Choosing wrong leads to bloated bundles, poor tree-shaking, or lost type safety.

Solution

Default to string literal unions: type Status = 'active' | 'inactive' | 'pending'. They're zero-cost at runtime, tree-shake perfectly, and work with JSON naturally. Use const objects + typeof when you need runtime values AND type safety: const Status = { Active: 'active', Inactive: 'inactive' } as const; type Status = typeof Status[keyof typeof Status]. Avoid regular enum — it generates runtime code and doesn't tree-shake. Never use const enum — it requires specific tsconfig flags and breaks with --isolatedModules (used by most bundlers).

Why

Regular enums compile to IIFEs that bundlers can't tree-shake. const enums are inlined but require the enum declaration to be available at compile time, which fails across package boundaries.

Code Snippets

Zero-cost type-safe alternatives to enum

// Preferred: string union
type Status = 'active' | 'inactive' | 'pending';

// When you need runtime values:
const Status = { Active: 'active', Inactive: 'inactive' } as const;
type Status = typeof Status[keyof typeof Status];

Revisions (0)

No revisions yet.