import * as vi from 'vitest'
import { z } from 'zod'
import { zx } from '@traversable/zod'
const MySchema = z.object({
abc: z.tuple([
z.literal(123),
z.set(z.array(z.number()))
]),
def: z.string(),
ghi: z.number(),
jkl: z.boolean(),
mno: z.optional(z.object({
pqr: z.record(z.enum(['P', 'Q', 'R']), z.number()),
}))
})
vi.assert.deepEqual(
zx.defaultValue(MySchema), {
abc: [123, new Set([[]])],
def: undefined,
ghi: undefined,
jkl: undefined,
mno: {
pqr: { P: undefined, Q: undefined, R: undefined }
}
})
vi.assert.deepEqual(
zx.defaultValue(
MySchema, {
fallbacks: {
number: 0,
boolean: false,
string: ''
}
}),
{
abc: [123, new Set([[]])],
def: '',
ghi: 0,
jkl: false,
mno: {
pqr: { P: 0, Q: 0, R: 0 }
}
}
)
zx.defaultValue
Derive a defaultValue from a zod schema (v4, classic).
By default,
zx.defaultValue
returnsundefined
for primitive values.If you'd like to change that behavior, you can pass a set of fallbacks via Options
Options['fallbacks']
Unions are special cases -- by default,
zx.defaultValue
simply picks the first union, and generates a default value for it. You can configure this behavior via OptionsOptions['unionTreatment']
.