import { assert } from 'vitest'
import { z } from 'zod'
import { zx } from '@traversable/zod'
const Address = z.object({
street1: z.string(),
street2: z.optional(z.string()),
city: z.string(),
})
const deepClone = zx.deepClone(Address)
const sherlock = { street1: '221 Baker St', street2: '#B', city: 'London' }
const harry = { street1: '4 Privet Dr', city: 'Little Whinging' }
const sherlockCloned = deepClone(sherlock)
const harryCloned = deepClone(harry)
// values are deeply equal:
assert.deepEqual(sherlockCloned, sherlock) // ✅
assert.deepEqual(harryCloned, harry) // ✅
// values are fresh copies:
assert.notEqual(sherlockCloned, sherlock) // ✅
assert.notEqual(harryCloned, harry) // ✅
zx.deepClone
Derive a "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
assumes that both values have already been validated. Passing invalid data to the deepClone function will result in undefined behavior.Note that
zx.deepClone
works in any environment that supports defining functions using theFunction
constructor. If your environment does not support theFunction
constructor, usezx.deepClone_writeable
.See also:
zx.deepClone.writeable