8000 v4: `isOptional` may throw despite using `safeParse` · Issue #4159 · colinhacks/zod · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

v4: isOptional may throw despite using safeParse #4159

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

Closed
RobinTail opened this issue Apr 15, 2025 · 3 comments
Closed

v4: isOptional may throw despite using safeParse #4159

RobinTail opened this issue Apr 15, 2025 · 3 comments

Comments

@RobinTail
Copy link
Contributor
RobinTail commented Apr 15, 2025

Current implementation:

inst.isOptional = () => inst.safeParse(undefined).success;

despite using safeParse (which is implying to be safe), still can trow this thing:

$ZodAsyncError {
  "message": "Encountered Promise during synchronous parse. Use .parseAsync() instead.",
}

It did not happen in v3.

Maybe it should be catched by safeParse?

@colinhacks
Copy link
Owner

Zod 3 does actually throw true Errors in this situation. This isn't a validation error, it's a user error, and so it should throw a real error. Otherwise users may think their code is working correctly when in fact it's incapable of validating any data propertly.

Image

I'd be curious what code produces different behavior in Zod 3 vs Zod 4.

@RobinTail
Copy link
Contributor Author
RobinTail commented Apr 20, 2025

I'd be curious what code produces different behavior in Zod 3 vs Zod 4.

@colinhacks ,

the following code does not throw with Zod 3 but it does with Zod 4:

z.promise(z.any()).isOptional();

This isn't a validation error

And I'm not even validating anything. I'm asking Zod if the schema is optional. It is Zod who is using safeParse to figure that out and it throws despite using its own method implying to be safe (not requiring try..catch).

@colinhacks
Copy link
Owner

I've deprecated these with an appropriate recommendation. These are undocumented utility methods so I'm not too worried about it.

Image

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

2 participants
0