Add method to preserve readonly props after call to extend #3533
+115
−13
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
The only way to have object properties marked as
readonly
is to call thereadonly()
method, but this results in aZodReadonly
object which cannot be extended via theextend()
method. Themerge()
method does not preserve thereadonly
markers. TheobjectUtil.mergeShapes()
sort of achieves the desired result, however the resulting object is not compatible withZodSchema<T>
and thus can't be passed as a parameter to a method that expectsZodSchema<T>
This change adds the
readonlyProps()
method toZodObject
which results in a projection of theZodObject
with all fields markedreadonly
.Additionally, the handling of the
Output
type parameter was changed so that when usingz.infer
the resulting type to has thereadonly
markers preserved.The
readonlyProps
method could be extended in the future to allow for a list of properties to be specified which would allow only specific props to be markedreadonly
. However, it's easy enough to useextend()
that this would be only a convenience.Many many many alternative approaches were considered, such as overloading the
readonly()
method to return aZodReadonlyObject
class which would have anextend()
method. IMO, this is not a good solution because the semantics of thereadonly()
are to freeze, and render readonly, the value, not the property assignment.This solution works very well for my usecase where a common base object contains
readonly
properties.