我有以下鉴别联合:
enum Option {
FULL = 'FULL',
TIME_PERIOD = 'TIME_PERIOD',
MONTH = 'MONTH',
}
const schema = z.discriminatedUnion('option', [
z.object({ option: z.literal(Option.FULL) }),
z.object({
option: z.literal(Option.TIME_PERIOD),
from: z.date(),
to: z.date(),
}),
z.object({ option: z.literal(Option.MONTH), month: z.date() }),
])
现在我想细化第二个对象,检查日期from
是否在to
之前:
const schema = z.discriminatedUnion('option', [
z.object({ option: z.literal(Option.FULL) }),
z.object({
option: z.literal(Option.TIME_PERIOD),
from: z.date(),
to: z.date(),
}).refine(
({ from, to }) => isBefore(from, to),
{
message: '"from" must be before "to"',
path: ['from'],
}
),
z.object({ option: z.literal(Option.MONTH), month: z.date() }),
])
但是这给了我一个错误,基本上说&;type zodeeffects是不允许作为zoddiscriminatedunionoption&;
我如何在验证中实现期望的行为?
这是我的问题的代码盒:https://codesandbox.io/s/zod-refine-in-discriminated-union-5kve15
解决方案是改进被区分的联合本身,而不是联合中的选项:
const schema = z.discriminatedUnion('option', [
z.object({ option: z.literal(Option.FULL) }),
z.object({
option: z.literal(Option.TIME_PERIOD),
from: z.date(),
to: z.date(),
}),
z.object({ option: z.literal(Option.MONTH), month: z.date() }),
]).refine(
(data) => {
if (data.option === Option.TIME_PERIOD) {
return isBefore(data.from, data.to)
}
return true
},
{
message: '"from" must be before "to"',
path: ['from'],
}
)