Feature: Formalize Zod Extensions
See original GitHub issueThere is a growing ecosystem around extending zod in various ways. This is awesome! However, these extensions are often awkward to work with. The underlying problem is that they cannot attach data to a zod type. I understand not wanting a general “metadata” property on zod types because this is ripe for abuse. However, could Zod be made extensible in some first class way?
Syntactically I was envisioning something like
const productNameSchema = z.string().ext.setMockFn(() => faker.commerce.productName())
const myProductName = productNameSchema.ext.mock() // returns product name
// or
const foo = z.date().ext.toFormikSchema()
where ext is an object which extensions add to.
Note: for typescript support to work with this, we would have to wrap Zod type in some way which would allow passing in Extensions (export would then be zod with no extensions).
To construct your extended Zod version, you could do something like
export const z = MakeZod([zodMockingExt, zodFormikExt, ...])
My hope would be that this could provide a definite pattern for how to extend zod leading to more consistency, a wider community, and perhaps even interoperable extensions.
Issue Analytics
- State:
- Created 2 years ago
- Reactions:2
- Comments:7 (3 by maintainers)
Top GitHub Comments
@colinhacks - What are your thoughts on adding the ability to patch zod in some type safe way? At Marcato, we have been adding ways to create and mock zod types but are discontent with look and feel of the code. It is inevitably very verbose and easy to make subtle mistakes. Depending on the implementation, would you support adding an official notion of “Zod Extensions”?
Hi @scotttrinh - I can see what you’re saying, and I realize I was assuming a feature of this mock extension which I never mentioned. Namely, I was assuming that the mock extension would have a default implementation for all zod types.
If that were true by default something like this would work…
And in our example above
If the consumer always had to write custom mock functions for their types, I agree that signal-to-noise ratio is equivalent. However, in the case where a default mock function is supplied by the extension, I believe the code required to make the example above work would be much simpler.