import { z } from 'zod'
import { zx } from '@traversable/zod'
const deepClone = zx.deepClone.writeable(
z.object({
street1: z.string(),
street2: z.optional(z.string()),
city: z.string(),
}), { typeName: 'Address' }
)
console.log(deepClone)
// =>
// type Address = { street1: string; street2?: string; city: string; }
// function deepClone(prev: Address) {
// return {
// street1: prev.street1,
// ...prev.street2 !== undefined && { street2: prev.street2 },
// city: prev.city
// }
// }
zx.deepClone.writeable
Derive a "writeable" (stringified) "deep clone" function from a zod schema (v4, classic).
The generated cloning function is significantly faster than JavaScript's built-in structuredClone
structuredClone
:It's even faster when compared with Lodash's
deepCloneDeep
:This is possible because the cloning function knows the shape of your data ahead of time, and will do the minimum amount of work necessary to create a new copy of your data.
Note that the deep clone function generated by
zx.deepClone.writeable
assumes that both values have already been validated. Passing invalid data to the deepClone function will result in undefined behavior. You don't have to worry about this as long as youzx.deepClone.writeable
accepts an optional configuration object as its second argument; documentation for those options are available via hover on autocompletion.See also:
zx.deepClone