Convert Prisma enum to Typescript enum (and opposite)

Hey guys, I have this Prisma enum:
enum ChallengeMetric {
STEP_COUNT
DISTANCE
VERTICAL_DURATION
WALK_DURATION
}
enum ChallengeMetric {
STEP_COUNT
DISTANCE
VERTICAL_DURATION
WALK_DURATION
}
And also this typescript enum:
export enum ChallengeMetric {
STEP_COUNT,
DISTANCE,
VERTICAL_DURATION,
WALK_DURATION
}
export enum ChallengeMetric {
STEP_COUNT,
DISTANCE,
VERTICAL_DURATION,
WALK_DURATION
}
The typescript is mainly used by my front. My backend have a class to convert my front object to Prisma typescript object. My problem is I don't know how to convert from my typescript enum to the prisma enum, and transform the prisma enum to my enum. The only solution that doesn't trigger an typescript error (not tested tho) is:
// Metric is my custom enum, PChallengeMetric is the Prisma enum
metric as unknown as keyof typeof PChallengeMetric,
// Metric is my custom enum, PChallengeMetric is the Prisma enum
metric as unknown as keyof typeof PChallengeMetric,
But it does not work (return undefined)
3 Replies
Prisma AI Help
Prisma AI Help6mo ago
You decided to hold for human wisdom. We'll chime in soon! Meanwhile, #ask-ai is there if you need a quick second opinion.
Nurul
Nurul6mo ago
Did you have a look at this related GitHub Discussion: https://github.com/prisma/prisma/discussions/9215
GitHub
Typescript Enum is not assignable to Prisma Enum · prisma prisma ...
my schema enum Role { USER ADMIN } my Role domain enum Role { USER, ADMIN, } export { Role } My prisma repository import { Role as PrismaRole } from '.prisma/client' import { Role as Domain...
DollarNavalex
DollarNavalexOP6mo ago
Yes but I don't think it talks about classic integer enums. But here is the solution I have: From Prisma enum to Typescript int enum:
static prismaToInt(value: PrismaEnum): MyEnum {
return MyEnum[value as keyof typeof MyEnum]
}
static prismaToInt(value: PrismaEnum): MyEnum {
return MyEnum[value as keyof typeof MyEnum]
}
From Typescript int enum to Prisma enum:
static intToPrisma(value: MyEnum): PrismaEnum {
const keys = Object.keys(PrismaEnum) as Array<keyof typeof PrismaEnum
return PrismaEnum[keys[value]]
}
static intToPrisma(value: MyEnum): PrismaEnum {
const keys = Object.keys(PrismaEnum) as Array<keyof typeof PrismaEnum
return PrismaEnum[keys[value]]
}
The only bad thing I found with this solution is that I can't use generic types, since I'm not using it only as type but also as values :/ So I have to make this function for each enum I have

Did you find this page helpful?