const schema = z.object({
id: z.string(),
name: z.string(),
});
相当于
type schema = {
id: string;
name: string;
}
我的问题是,我必须将一些属性设为可选,但要保持这样的类型
type schema = {
id?: string;
name: string;
}
如果我使用
.optional()
,它将使所有属性可选
目的是,我需要
schema
从数据库返回所以 id
不为空 pk.
案例:我有upsert方法
user.upsert({ ...schemaInput, id: schemaInput?.id || generateId() })
但是每次我执行该方法时,zod parser 总是显示错误
{
"expected": "string",
"received": "undefined",
"path": [
"id"
],
}
您只需将该属性的值设置为可选。当该值用作对象属性时,Zod 会注意到这一点,并使该属性对您来说是可选的。
const schema = z.object({
id: z.string(),
name: z.string().optional(),
});
const value = schema.parse({ id: 'abc' })
// value has type { id: string, name?: string | undefined }