Back to Snippets
TypeScriptTypeScript

TypeScript Enum Alternatives

Type-safe alternatives to enums using const objects and union types.

typescriptenumconstpattern
class=class="text-emerald-400">"text-gray">// Instead of: enum Status { Active, Inactive, Pending }
class=class="text-emerald-400">"text-gray">// Use a const object:
const Status = {
  Active: class=class="text-emerald-400">"text-emerald-400">'active',
  Inactive: class=class="text-emerald-400">"text-emerald-400">'inactive',
  Pending: class=class="text-emerald-400">"text-emerald-400">'pending',
} as const

type Status = (typeof Status)[keyof typeof Status]
class=class="text-emerald-400">"text-gray">// Result: class=class="text-emerald-400">"text-emerald-400">'active' | class=class="text-emerald-400">"text-emerald-400">'inactive' | class=class="text-emerald-400">"text-emerald-400">'pending'

class=class="text-emerald-400">"text-gray">// With display labels
const StatusLabel: Record<Status, string> = {
  active: class=class="text-emerald-400">"text-emerald-400">'Active',
  inactive: class=class="text-emerald-400">"text-emerald-400">'Inactive',
  pending: class=class="text-emerald-400">"text-emerald-400">'Pending',
}

class=class="text-emerald-400">"text-gray">// Type guard
function isStatus(value: string): value is Status {
  return Object.values(Status).includes(value as Status)
}

class=class="text-emerald-400">"text-gray">// Usage
function getLabel(status: Status): string {
  return StatusLabel[status]
}

console.log(getLabel(Status.Active)) class=class="text-emerald-400">"text-gray">// class=class="text-emerald-400">"text-emerald-400">'Active'

How to Use

Replace enums with const objects for better tree-shaking and type inference. The pattern gives you autocompletion, type safety, and the values are plain strings that work naturally with JSON serialization.

Related Technology

TypeScript

Have a Project in Mind?

Let's discuss how we can bring your idea to life. From initial concept to production-ready product — we've got you covered.

or book a free call