使用zod时的注意:nullable vs optional

1 min read
定义zod schema的时候,有时候定义为nullable
时要注意:如果你是从一个可能为空的对象里取出一个字段来parse
的时候,可能会出现问题:
const schema = z.object({
a: z.string().nullable()
});
const rawData = {
nested: null
};
const data = schema.parse({
a: rawData.nested?.a
});
会导致throw,程序无法继续下去。
解决办法:
schema设置为
nullable().optional()
传参时
rawData.nested?.a ?? null
总结:
要注意null
和undefined
的区别。
0
Subscribe to my newsletter
Read articles from Landay directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
