Is there a better way to access enum types?

// the schema
export const MarketplaceIntegrationType = pgEnum('MarketplaceIntegrationType', [
'Amazon',
'Walmart',
'Etsy',
'Shopify'
]);
type: MarketplaceIntegrationType('type').notNull()

// the code
let integrationType: typeof marketplaceIntegrations.$inferSelect.type;
// the schema
export const MarketplaceIntegrationType = pgEnum('MarketplaceIntegrationType', [
'Amazon',
'Walmart',
'Etsy',
'Shopify'
]);
type: MarketplaceIntegrationType('type').notNull()

// the code
let integrationType: typeof marketplaceIntegrations.$inferSelect.type;
is there a better way to do this other than manually creating a type to use everywhere? its not very ergonomic to type this out like that i can also do something like
(typeof MarketplaceIntegrationType.enumValues)[number]
(typeof MarketplaceIntegrationType.enumValues)[number]
but this sucks too
4 Replies
Angelelz
Angelelz11mo ago
What I do is I create the array as const, create the type from it, and then pass it to the pgEnum function
const marketPlaceIntegrationTypes = [
'Amazon',
'Walmart',
'Etsy',
'Shopify'
] as const;
type MarketPlaceIntegrationTypes = typeof marketPlaceIntegrationTypes;
export const MarketplaceIntegrationType = pgEnum('MarketplaceIntegrationType', marketPlaceIntegrationTypes);
const marketPlaceIntegrationTypes = [
'Amazon',
'Walmart',
'Etsy',
'Shopify'
] as const;
type MarketPlaceIntegrationTypes = typeof marketPlaceIntegrationTypes;
export const MarketplaceIntegrationType = pgEnum('MarketplaceIntegrationType', marketPlaceIntegrationTypes);
jakeleventhal
jakeleventhalOP11mo ago
then how do you get the types in code? just MarketplaceIntegrationTypes[number]
Angelelz
Angelelz11mo ago
Oh yeah, forgot that, the type should have [number] at the end
Amur
Amur3mo ago
coming back to this conversation as i feel like working with enums is still annoying as you mentioned above we can do this workaround to get the types but what if i have a function and i want to check if the maketPlaceIntegration is Amazon with a typescript enum i would have something like this but this is not possible with pgEnum
const isAmazon = (integration: MarketPlaceIntegrationTypes) => {
if(integration === MarketPlaceIntegrationTypes.Amazon){
// do something
}
}
const isAmazon = (integration: MarketPlaceIntegrationTypes) => {
if(integration === MarketPlaceIntegrationTypes.Amazon){
// do something
}
}
Want results from more Discord servers?
Add your server