prisma-zod-generator
prisma-zod-generator copied to clipboard
Re-use Zod Schemas as a z.ZodObject not z.ZodType
Problem
Generated schemas are not reusable (pick/omit/extend/etc) because the schema infers a type and is not considered a ZodObject anymore. An example...
const Schema: z.ZodType<Prisma.TodoCreateInput> = z.object({
title: z.union([
z.string(),
z.lazy(() => StringFieldUpdateOperationsInputObjectSchema),
])
}).strict();
export const TodoCreateInput = Schema;
In the above, it is impossible to use TodoCreateInput.extend(), etc because the type z.ZodType<...> is being inferred.
Suggested solution
There was a similar discussion in the Zod repo in 1192 and a solution in 1495.
One solution is to change the example above to resolve like the one below. I haven't fully tested this but it seems to work with my simple examples:
const Schema = z.object({
title: z.union([
z.string(),
z.lazy(() => StringFieldUpdateOperationsInputObjectSchema),
])
}).strict() satisfies z.ZodType<Prisma.TodoCreateInput>;
export const TodoCreateInput = Schema;
Alternatives
Alternatively, the Schema could be created as a ZodObject and exported as such, and then the ZodType exported separately. This way we can do what we want with the schema or export it as a type. Best of both worlds.
export const TodoCreateInputSchema = z.object({
title: z.union([
z.string(),
z.lazy(() => StringFieldUpdateOperationsInputObjectSchema),
])
}).strict();
export const TodoCreateInputSchemaType: z.ZodType<Prisma.TodoCreateInput> = Schema;
Additional context
No other context.
Ran into this problem today - definitely support this RFC.