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];
}Report a problem with this exampleOpens a pre-filled issue on GitHub.