Schemas and optionality #3938
mike-wheel
started this conversation in
General
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hey folks!
Rich Hickey talks about how most type systems (including zod and Typescript) conflate the ideas of schema and optionality. The issue is that a schema is a shape of an entity, regardless of optionality (
undefined
/null
) which can differ at different call sites. We use.optional()
/.nullable()
, etc, when we define our schemas. This locks certain keys into being optional forever and ever, no matter what call site. In reality, some places requirefoo
and some don't care aboutfoo
. This leads to type proliferation and divergence of types in places that should be able to leverage a shared schema.(watch this part of this video for more details)
I was hoping
zod
had a concise way to update the optionality of a schema so that can we customize the requirements for each call site. The best I've found so far withzod
is to define a schema without optionality, then use.partial()
and.required()
to select the required fields at a given call site.This is close, but it only works with
undefined
s..partial()
will make all fields.optional()
and.required()
will undo it for the fields that we care about. I don't see azod
equivalent to.partial()
that makes each entry.nullable()
or.nullish()
.Another larger issue with it is that it doesn't extend deeply into aggregates. For example, if one of the keys was
address
and I only require thezip
, this pattern breaks down.The ideal situation would be to have the ability to define schemas regardless of optionality and have tools to deeply specify only the required fields at each different call site.
Does anyone have any thoughts about this?
Beta Was this translation helpful? Give feedback.
All reactions