Shrink TypeScript Code: Replace Enums with Const Objects
Briefly

Shrink TypeScript Code: Replace Enums with Const Objects
"Enums look elegant, but they secretly bloat your JavaScript output. Each one compiles into a function wrapper that adds unnecessary weight to your bundle. Example: // Old way with enums enum PaymentMethod { Credit = 'credit', Debit = 'debit', Cash = 'cash', } Usage: const method = PaymentMethod.Credit; After compilation: var PaymentMethod; (function (PaymentMethod) { PaymentMethod["Credit"] = "credit"; PaymentMethod["Debit"] = "debit"; PaymentMethod["Cash"] = "cash"; })(PaymentMethod || (PaymentMethod = {})); Each key creates more boilerplate. In large projects with dozens of enums, this overhead adds up."
"const PaymentMethod = { Credit: 'credit', Debit: 'debit', Cash: 'cash', } as const; type PaymentMethod = keyof typeof PaymentMethod; const method: PaymentMethod = PaymentMethod.Credit; Still type-safe Works with IntelliSense Generates minimal JavaScript const FormStatus = { Idle: 'idle', Submitting: 'submitting', Success: 'success', Error: 'error', } as const; type FormStatus = keyof typeof FormStatus; function renderForm(status: FormStatus) { console.log(`Form is ${status}`); } renderForm(FormStatus.Success);"
Enums compile into function wrappers that add boilerplate and increase JavaScript bundle size. Each enum key generates additional compiled code, which accumulates in large projects. Replacing enums with const objects plus a type alias preserves type safety and IntelliSense while emitting minimal JavaScript. Use "keyof typeof" to produce a union of keys for string-based constants. For value-based sets use "typeof X[keyof typeof X]" to get the value union. Reverse mappings are not automatic with const objects, so a simple helper can be written when reverse lookup is required.
Read at jsdevspace.substack.com
Unable to calculate read time
[
|
]