Coerced Enums #730
Replies: 2 comments
-
Just wrote something very similar. It may be a nice addon for zod to export its |
Beta Was this translation helpful? Give feedback.
-
Thanks for the idea! I was trying to find a way to mark a field as an enum but if it's not in the list of values, default it to a specific value and came up with this based on your code: function zodEnumWithDefault<Value extends string, EnumsArray extends Readonly<[Value, ...Value[]]>>(
values: EnumsArray,
defaultValue: EnumsArray[number]
) {
return z.preprocess((incomingValue) => {
if (typeof incomingValue === "string") {
if (values.includes(incomingValue as Value)) {
return incomingValue;
}
return defaultValue;
}
return null;
}, z.enum(values));
} |
Beta Was this translation helpful? Give feedback.
-
We're using zod with Prisma and Blitz. We were wanting our queries/mutations to be able to accept enums from our prisma schema as well as other enums we have defined. Some of these enums come from the url query parameters or are user-modifiable, so we didn't want to be case sensitive. We've been using this coerced enum helper and thought it might be useful to others:
Beta Was this translation helpful? Give feedback.
All reactions