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
Andrii Sherman16mo ago
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
rushil1o116mo ago
We usually pass enums into zod.nativeEnum() for validation
rushil1o1
rushil1o116mo 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
Andrii Sherman16mo ago
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 ?
bloberenober
bloberenober16mo 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
rushil1o116mo ago
I think its a common use case - but yeah I can manually support it for now thanks!
rphlmr ⚡
rphlmr ⚡16mo ago
sorry for intruding, is this the right way? pgEnum doesn't accept array as const 🧐
No description
bloberenober
bloberenober16mo 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
rushil1o116mo 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
Dave13mo ago
Is there any update on getting typescript types for enums from Drizzle?
DrPotat
DrPotat11mo 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
More Posts