我想验证来自后端的数据,我希望这些数据类似于这个类型记录的形状。
export interface Booking {
locationId: string;
bookingId: number;
spotId: string;
from: string;
to: string;
status: "pending" | "confirmed" | "closed";
}因此,我编写了zod模式和一个验证器函数,如下所示:
const bookingOnLoadResponse = z.array(
z.object({
locationId: z.string(),
bookingId: z.number(),
spotId: z.string(),
status: z.literal("pending" || "confirmed" || "closed"),
from: z.string(),
to: z.string(),
})
);
export function bookingOnLoadValidator(bookingArray: unknown) {
return bookingOnLoadResponse.parse(bookingArray);
}现在我知道了状态字段的问题,就像最近添加的那样,我在日志中看到响应中缺少这个字段,但是从Zod我得到的全部信息是:
[Unhandled promise rejection: ZodError: []
at http://10.3.42.237:19000/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false&strict=false&minify=false:226607:293 in _createSuperInternal
at node_modules/zod/lib/ZodError.js:29:8 in constructor
at node_modules/zod/lib/types.js:29:22 in handleResult
at node_modules/zod/lib/types.js:120:23 in ZodType#parse
at utils/zodSchemas/bookingResponseSchema.ts:16:9 in bookingOnLoadValidator
at utils/fetchFunctions.ts:28:9 in fetchBookings有什么方法可以更详细地描述问题的原因吗?谢谢
发布于 2022-09-20 04:12:15
我的猜测是,拒绝承诺是parse抛出的结果。如果从承诺的回调或从async函数调用它,那么最终的结果将是拒绝承诺。
如果parse不能解析您指定的模式,它将抛出。如果您的数据形状与您预期的有任何不同,那么它将抛出。很难确切地说它为什么在没有看到JSON的情况下抛出,但我猜您对status的定义是不正确的。
||将被计算为逻辑或表达式,因此"pending" || "confirmed" || "closed"将解析为"pending" (因为“未决”是the y,||将解析到链中的第一个值,即the y)。正因为如此,状态的其他值将导致解析失败。
试一试
status: z.enum(["pending", "confirmed", "closed"]),https://stackoverflow.com/questions/73773563
复制相似问题