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

Add runtime introspection of the constructor provided to z.instanceof #3500

Open
6XGate opened this issue May 18, 2024 · 0 comments
Open

Add runtime introspection of the constructor provided to z.instanceof #3500

6XGate opened this issue May 18, 2024 · 0 comments

Comments

@6XGate
Copy link

6XGate commented May 18, 2024

Introduction

When using other tooling with Zod, it would be great if that tooling could introspect the schema for z.instanceof to determine the constructor that was provided to it. This would allow such tooling to act on that constructor in many ways; for example, a serialization library may want to support some instances of certain built-ins for which Zod does not have dedicated schema factories.

Solution

Create a dedicated z.ZodInstanceOf class to handle instanceof validation. Add a ctor or other appropriate name to store a reference to the constructor or class. Note that constructor cannot be used as it would collide with the existing shape of the prototype of any instance.

Rational

Currently, z.instanceof creates a schema via z.custom which is just a superRefine against z.ZodAny. This eliminates any data that could be used for introspection since non is passed on to the z.ZodAny. Creating a dedicated class for the instanceof schema would allow introspection of the what constructor it was created with.

Caveat

Changing current implementation of z.instanceof could be a major breaking change, but it is also likely very little of the tooling community built around Zod really does much with z.ZodAny in relation to custom schema since introspection is very limited. This could be a Zod v4 feature where breaking changes are expected.

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