如何为深度嵌套的对象编写模式



我有以下数据:

{
"2022-06-01": {
"09:00am": {
"time_table_id": 1,
"job_id": 4,
"start_working_time": "09:00am",
"end_working_time": "09:00pm",
"work_duration": "12:00:00",
"merchant_name": "Brands Outlet @ The Starling",
"address2": "Jalan SS 21/37, Damansara Utama",
"job_name": "Pro hero",
"job_application_status": "Hired"
}
}
}

,这是我的模式,但它给了我一个zod错误。

const apiScheme = z.object({
Date: z.object({
Time: z.object({
date: z.string(),
time_table_id: z.number().nullable(),
job_id: z.number(),
start_working_time: z.string(),
end_working_time: z.string(),
// work_duration: z.string(),
// merchant_name: z.string(),
// address2: z.string(),
job_name: z.string(),
job_application_status: z.string(),
}),
}),
});
// -- snip -- (React code):
const data = useMemo(() => {
if (responseData) {
const parseData = apiScheme.parse(responseData);
//    error here ~~~~~~~~~~-^
if (parseData) {
return parseData;
}
}
return null;
}, [responseData]);

我认为你的问题是,当你实际想要使用z.record时,你正在使用z.object类型。

const apiSchema = z.record(
z.string(), // Key type for the outer record
z.record(
z.string(), // Key type for the second level record
z.object({
time_table_id: z.number().nullable(),
job_id: z.number(),
start_working_time: z.string(),
end_working_time: z.string(),
work_duration: z.string(),
merchant_name: z.string(),
address2: z.string(),
job_name: z.string(),
job_application_status: z.string()
}),
),
);

z.object用于内部大多数对象的模式等情况,其中所有字段名称都是已知的并且将保持不变。z.record是使用当你有一个类型,如TypeScript的记录类型,这只是一个对象,是可索引的,但对象的实际键在编译时不知道。


小一边如果你在编译时知道这些值总是相同的日期和时间,你可以这样写模式:

z.object({
"2022-06-01": z.object({
"09:00am": z.object({ /* ... */ }),
},
});

但是我假设"日期"one_answers";Time"索引在编译时是未知的。像上面这样的模式也应该解析示例中的确切数据形状(但如果其中一个日期或时间不同,则会失败)。

最新更新