新的打字稿,Zod & Trpc。
假设我对动物和植物都有一个模式。我希望将它们的所有公共属性存储在模式的“根”中,然后将更具体的属性放入名为custom的子对象中。(只是一个简化事情的虚构例子)
到目前为止我有这样的想法:
create: t.procedure
.input(z.object({
id: z.string(),
type: z.string(), //can be "ANIMAL" or "PLANT"
//all other common properties go here
//...
custom: z.object({ fur: z.string() }) //...if it's an animal, it will have "fur" here, if it's a plant something entirely different, like "seeds"
}).nullish())我不明白如何让这件事起作用,也不明白如何用zod来完成这件事。我研究了zods歧视联盟,但我似乎不完全理解语法是如何工作的?
发布于 2022-11-05 00:29:14
这是您何时使用discriminatedUnion的一个很好的例子。
例如:
const inputSchema = z.discriminatedUnion("type", [
z.object({
id: z.string(),
type: z.literal('ANIMAL'),
custom: z.object({ fur: z.string() }),
}),
z.object({
id: z.string(),
type: z.literal('PLANT'),
custom: z.object({ seeds: z.number() }),
})
]).nullish();然后,您可以将该模式传递到input()。如果您有很多共享字段,您可以将这些字段存储在一个基本模式中,而不是将它们复制到每个分支中,然后将其放在一个merge中。
https://stackoverflow.com/questions/74320261
复制相似问题