prisma-zod-generator icon indicating copy to clipboard operation
prisma-zod-generator copied to clipboard

Re-use Zod Schemas as a z.ZodObject not z.ZodType

Open owenr88 opened this issue 2 years ago • 1 comments
trafficstars

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.

owenr88 avatar Oct 19 '23 14:10 owenr88

Ran into this problem today - definitely support this RFC.

Handfish avatar Oct 26 '23 14:10 Handfish