import * as vi from 'vitest'
import * as v from 'valibot'
import { vx } from '@traversable/valibot'
const MySchema = v.object({
abc: v.tuple([
v.literal(123),
v.set(
v.array(v.number())
)
]),
def: v.string(),
ghi: v.number(),
jkl: v.boolean(),
mno: v.optional(v.object({
pqr: v.record(
v.enum(['P', 'Q', 'R']),
v.number()
),
}))
})
vi.assert.deepEqual(
vx.defaultValue(MySchema),
{
abc: [123, new Set([[]])],
def: undefined,
ghi: undefined,
jkl: undefined,
mno: {
pqr: {
P: undefined,
Q: undefined,
R: undefined
}
}
}
)
vi.assert.deepEqual(
vx.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 }
}
}
)
vx.defaultValue
Derive a default value from a Valibot schema.
By default,
vx.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,
vx.defaultValue
simply picks the first union, and generates a default value for it. You can configure this behavior via OptionsOptions['unionTreatment']
.