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 method to preserve readonly props after call to extend #3533

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

llowrey
Copy link

@llowrey llowrey commented May 26, 2024

The only way to have object properties marked as readonly is to call the readonly() method, but this results in a ZodReadonly object which cannot be extended via the extend() method. The merge() method does not preserve the readonly markers. The objectUtil.mergeShapes() sort of achieves the desired result, however the resulting object is not compatible with ZodSchema<T> and thus can't be passed as a parameter to a method that expects ZodSchema<T>

This change adds the readonlyProps() method to ZodObject which results in a projection of the ZodObject with all fields marked readonly.

Additionally, the handling of the Output type parameter was changed so that when using z.infer the resulting type to has the readonly 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 marked readonly. However, it's easy enough to use extend() that this would be only a convenience.

Many many many alternative approaches were considered, such as overloading the readonly() method to return a ZodReadonlyObject class which would have an extend() method. IMO, this is not a good solution because the semantics of the readonly() 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.

Results in a ZodObject with all properties tagged with readonly.

The readonly tagging will be preserved if the .extend method is called.
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

Successfully merging this pull request may close these issues.

None yet

1 participant