Skip to Content

defineEnum

Declare a list of statuses or categories once, with labels and colours, and use it on the server and in the UI.

Usage

app/shared/order.ts
import { defineEnum } from "manh/enum"; export const OrderStatus = defineEnum({ pending: ["Pending", "processing"], done: ["Done", "success"], cancelled: ["Cancelled", "default"], }); export type OrderStatus = (typeof OrderStatus.values)[number];

Put it in app/shared/ so both .tsx pages and .ts handlers can import it.

Signature

manh/enum
type EnumColor = "success" | "error" | "processing" | "warning" | "default" | (string & {}); function defineEnum<const T extends Record<string, readonly [label: string, color?: EnumColor]>>(def: T): { readonly values: [K, ...K[]]; label(v: K | string | null | undefined): string; color(v: K | string | null | undefined): EnumColor | undefined; readonly valueEnum: Record<K, { text: string; status?: string; color?: string }>; readonly options: Array<{ value: K; label: string }>; is(v: unknown): v is K; }; // K = the keys of def

Parameters

  • def: an object whose keys are the values stored in the database and whose values are [label, colour]. The colour is one of success, error, processing, warning, default (shown as a Badge) or any antd Tag colour ("blue", "#1677ff"). The colour is optional.

Returns

A read-only object:

  • values: the array of keys, for z.enum(X.values) and loops.
  • label(v): the label of a value. An unknown value comes back as a string.
  • color(v): the colour of a value, or undefined.
  • valueEnum: for the valueEnum of a ProTable or ProDescriptions column.
  • options: [{ value, label }] for Select, Segmented, Radio.
  • is(v): true when v is a declared key.

Examples

Server:

app/orders/[id:int]/status/post.ts
import { z } from "@hono/zod-openapi"; import { OrderStatus } from "app/shared/order"; export const schema = { body: z.object({ to: z.enum(OrderStatus.values) }) };

UI:

app/orders/order-columns.tsx
import { Tag } from "antd"; import { OrderStatus } from "app/shared/order"; export const statusColumn = { title: "Status", dataIndex: "status", valueEnum: OrderStatus.valueEnum }; export const StatusTag = ({ v }: { v: string }) => <Tag color={OrderStatus.color(v)}>{OrderStatus.label(v)}</Tag>;

Change a label here and every screen, filter, schema and email follows. Don’t redeclare the same list in a page or a handler.

Next steps

Last updated