Is there a simpler way to get an enum type than (typeof enumType)["enumValues"][number]?

Pretty quick question (and maybe quick answer) - we have this pattern in a few places and it looks a bit verbose.
2 Replies
Noahh
Noahh16mo ago
Not sure if this is what you mean, but we have this pattern:
export const orderMethodEnum = pgEnum('order_method', ['PICKUP', 'DELIVERY']);

export const OrderMethod = strEnum(orderMethodEnum.enumValues);

export type OrderMethodValue = keyof typeof OrderMethod;
export const orderMethodEnum = pgEnum('order_method', ['PICKUP', 'DELIVERY']);

export const OrderMethod = strEnum(orderMethodEnum.enumValues);

export type OrderMethodValue = keyof typeof OrderMethod;
This allows us to do stuff like OrderMethod.PICKUP and use OrderMethodValue as a type when excepting one of the values Sorry, meant to include strEnum
export const strEnum = <T extends string>(o: T[]): { [K in T]: K } => {
return o.reduce((res, key) => {
res[key] = key;
return res;
}, Object.create(null));
};
export const strEnum = <T extends string>(o: T[]): { [K in T]: K } => {
return o.reduce((res, key) => {
res[key] = key;
return res;
}, Object.create(null));
};
DrPotat
DrPotat15mo ago
Thanks a lot for sharing @Noahh - those snippets are super useful Another (indirect) way to get the enum values type is by inspecting the table's type:
// When MY_TABLE has a column called COLUMN
type MyEnumType = typeof MY_TABLE.$inferSelect.MY_ENUM_COLUMN
// When MY_TABLE has a column called COLUMN
type MyEnumType = typeof MY_TABLE.$inferSelect.MY_ENUM_COLUMN
For example:
export const orderMethodEnum = pgEnum("order_method", ["PICKUP", "DELIVERY"]);
const order = pgTable("order", {
method: orderMethodEnum("method").notNull(),
});
type OrderMethodValue = typeof order.$inferSelect.method;
export const orderMethodEnum = pgEnum("order_method", ["PICKUP", "DELIVERY"]);
const order = pgTable("order", {
method: orderMethodEnum("method").notNull(),
});
type OrderMethodValue = typeof order.$inferSelect.method;
I wish there was a way to get this type directly from the pgEnum though
Want results from more Discord servers?
Add your server