Const Object as Enum Alternative
Replace numeric enums with an as const object plus a derived union, giving readable runtime values and exhaustive compile-time checks.
Code
export const Status = {
Pending: "pending",
Active: "active",
Suspended: "suspended",
} as const;
export type Status = (typeof Status)[keyof typeof Status];
export function isTerminal(status: Status): boolean {
return status === Status.Suspended;
}
export function label(status: Status): string {
const labels: Record<Status, string> = {
[Status.Pending]: "Pending review",
[Status.Active]: "Active",
[Status.Suspended]: "Suspended",
};
return labels[status];
}Inside the snippet
Const Object as Enum Alternative is built around the functions isTerminal and label.
Putting it to use
Entry signature: export const Status =
Status is what another module would consume; nothing else here is load-bearing for callers.
Core lines
return status === Status.Suspended;
return labels[status];
Interactive Tools for This Topic
FAQ
- Is anything beyond the standard library required?
- Nothing beyond the standard library — the snippet is dependency-free. The file defines `isTerminal`, `label` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.