Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
owenr88 opened this issue Oct 19, 2023 · 1 comment · May be fixed by #89
Open

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

owenr88 opened this issue Oct 19, 2023 · 1 comment · May be fixed by #89

Comments

@owenr88
Copy link

owenr88 commented Oct 19, 2023

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.

@Handfish
Copy link

Ran into this problem today - definitely support this RFC.

owenr88 added a commit to owenr88/prisma-zod-generator that referenced this issue Oct 27, 2023
@owenr88 owenr88 linked a pull request Oct 27, 2023 that will close this issue
jkumara added a commit to Salesled/prisma-zod-generator that referenced this issue May 19, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants