You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TRPC中为content字段应用z.discriminatedUnion()?

解决方案

你可以通过在z.discriminatedUnion中定义每个类型对应的完整对象结构(包含公共字段+判别字段+匹配的content)来实现需求,既能保留id等公共属性,又能让content根据type的不同拥有对应的校验规则。

具体代码示例如下:

update: t.procedure
  .input(
    z.discriminatedUnion('type', [
      // blogPost 类型对应的结构
      z.object({
        id: z.string(),
        type: z.literal('blogPost'),
        content: z.object({
          title: z.string(),
          body: z.string(),
          tags: z.array(z.string())
        }).nullish()
      }),
      // landingPage 类型对应的结构
      z.object({
        id: z.string(),
        type: z.literal('landingPage'),
        content: z.object({
          title: z.string(),
          heroImage: z.string(),
          ctaText: z.string()
        }).nullish()
      })
    ]).nullish() // 保留原需求中整个输入可空的设定
  )

关键说明:

  • 用z.literal指定具体的type值作为判别标识,让Zod能根据type自动匹配对应的校验规则
  • 每个联合成员都包含公共字段id,以及对应类型专属的content结构
  • 最后给整个判别联合类型加上.nullish(),保持原代码中输入可空的逻辑

这样当传入type: 'blogPost'时,Zod会自动校验content是否符合博客文章的结构;传入type: 'landingPage'时则校验落地页的结构,同时id字段在所有类型中都必须是字符串格式。

内容的提问来源于stack exchange,提问作者antonwilhelm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 01:41:28