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

ZodCatch Rethrow #3824

Open
samchungy opened this issue Oct 30, 2024 · 0 comments
Open

ZodCatch Rethrow #3824

samchungy opened this issue Oct 30, 2024 · 0 comments

Comments

@samchungy
Copy link
Contributor

samchungy commented Oct 30, 2024

I was working on my library: https://github.com/samchungy/zod-openapi and was trying to simplify how I determine if a schema should be "required".

ZodCatch I initially thought I could handle as if nothing happened, however, it seems to accept undefined which makes it technically optional. I believe consumers should be able to mark this as a required schema since we have .default() to be able to handle undefined values.

I think it would be helpful for consumers to be able to catch the error, and to rethrow/or return a ZodError if they think it should be still flagged as invalid.

eg.

const schema = z.string().min(1).catch((ctx) => {
  if (ctx.input === undefined) {
    throw ctx.error;
  }
  return 'foo'
})

schema.safeParse(undefined); // Does not throw
schema.isOptional() // false

It would be akin to z.string().optional() with .refine() but your input boundary would be introspectable as non optional

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

No branches or pull requests

1 participant