Any easy way to create a typescript ENUM type from pgEnum?

Prisma used to auto-gen all the enum types as well which are heavily used in our application.
12 Replies
Andrii Sherman
Drizzle generates union type of strings, that we used in enums. Same for introspect. It generates schema file with enums, that were used on existing database Any examples why you want to use enum instead of 'foo' | 'bar'?
rushil1o1
rushil1o1OP2y ago
We usually pass enums into zod.nativeEnum() for validation
rushil1o1
rushil1o1OP2y ago
I guess we could use z.enum, but it'd still be nice to export enum types easily. is there any way I can convert pgEnum to an Enum type?
No description
Andrii Sherman
yeah, I guess you can just change nativeEnum to enum to check and get type we can provide helper for that, so you could generate type from string union. But it will be basically same as using zod any thoughts here @bloberenober @alexblokh ?
Dan
Dan2y ago
Enums are runtime values and unions are types, so it's not possible to generate enums from unions, only the other way around We can think about providing better enums support - we don't use them in our work projects so we didn't plan the ORM around them
rushil1o1
rushil1o1OP2y ago
I think its a common use case - but yeah I can manually support it for now thanks!
rphlmr ⚡
rphlmr ⚡2y ago
sorry for intruding, is this the right way? pgEnum doesn't accept array as const 🧐
No description
Dan
Dan2y ago
well... I'm not sure how it can be worked around for now, maybe with some type casting I definitely need to add support for readonly arrays to enums as the quickest fix
rushil1o1
rushil1o1OP2y ago
export function 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 testEnum = pgEnum("Test", ["test1", "test2"]);
export const Test = strEnum(testEnum.enumValues);
export type Test = keyof typeof Test;
export function 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 testEnum = pgEnum("Test", ["test1", "test2"]);
export const Test = strEnum(testEnum.enumValues);
export type Test = keyof typeof Test;
@Raphaël M (@rphlmr) ⚡ : this is the work around we have, you might have to create helpers for integer enums.
Dave
Dave2y ago
Is there any update on getting typescript types for enums from Drizzle?
DrPotat
DrPotat16mo ago
Btw @rushil1o1 here's another way to get the values type of a pgEnum, by inspecting the table types instead of using a helper like strEnum : https://discord.com/channels/1043890932593987624/1138161535416553585/1148743897690931400
Want results from more Discord servers?
Add your server