chrishoermann / zod-prisma-types

Generator creates zod types for your prisma models with advanced validation
Other
578 stars 43 forks source link

Expose "Unchecked" (and other) zod Objects as zod Objects #210

Closed nbibler closed 7 months ago

nbibler commented 7 months ago

zod Objects allow for object extension and manipulation via utilities like .pick()/omit() and .shape(), among many others. This library currently generates several zod Objects, but it tends to expose them as a zod Type to the application. zod Types are far more limited in functionality than zod Objects.

export const TableNameUncheckedCreateInputSchema: z.ZodType<Prisma.TableNameUncheckedCreateInput> =
  z
    .object({
      id: z.string(),
      secret: z.string(),
    })
    .strict()

I assume it was primarily done this way to ensure that the generated zod Object is compatible with the Prisma-generated type. But, there's a better way to do that since TypeScript 4.9+ and expose the actual zod Object to the application, via satisfies:

export const TableNameUncheckedCreateInputSchema =
  z
    .object({
      id: z.string(),
      secret: z.string(),
    })
    .strict() satisfies z.ZodType<Prisma.TableNameUncheckedCreateInput>

It would be hugely beneficial to expose the zod Objects directly to the application. Among other things, this would allow developers to more easily generate derived or extended Objects/schemas. This is useful, for example, to limit HTML form inputs to a subset of properties:

export const MyFormSchema = TableNameUncheckedCreateInputSchema.pick({ id: true });
// This is a Schema that disallows the `secret` to be passed, for instance.
chrishoermann commented 7 months ago

@nbibler thanks for the idea but sadly this is not possbile since the prisma types are heavily recurseive and zod needs this type annotation as a type hint to work correctly as stated in the zod docs

As you mentioned it would be very beneficial for DX but here's an example type error for a recursive schema when using satisfied:

image