zod icon indicating copy to clipboard operation
zod copied to clipboard

Add method to preserve readonly props after call to extend

Open llowrey opened this issue 9 months ago • 0 comments

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.

llowrey avatar May 26 '24 23:05 llowrey