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

如何从Zod对象Schema中获取子Schema?

从Zod对象Schema中提取字段子Schema进行单独验证

问题描述

我有如下Zod对象Schema:

const schema = z.object({
  name: z.string(),
  email: z.string()
})

后续代码中我只想验证email字段,是否可以通过类似schema.getSubschema("email").safeParse(...)的方式获取email对应的子Schema?我知道可以单独定义邮箱的Schema,但从已有的对象Schema中获取会更便捷。

补充的复杂Schema示例:

const saveHomeworkSchema = z
  .object({
    description: description,
    solution: description,
    video: file.optional(),
    images: files.optional(),
    domain: selectItem,
    theorems: theorems,
    definitions: definitions,
    tags: tags,
    isFree: z.any(),
    price: price,
    status: z.nativeEnum(HomeworkStatus),
  })
  .refine(
    (data) => data.solution || data.video || data.images?.length,
    'Musisz podać przynajmniej jeden format rozwiązania.'
  );

解决方案

Zod对象Schema内置了shape属性,直接通过该属性即可访问任意字段对应的子Schema,完全满足你的需求:

  1. 简单示例的实现
// 提取email字段的子Schema
const emailSchema = schema.shape.email;
// 单独验证email
const result = emailSchema.safeParse("test@example.com");
  1. 复杂Schema的实现
    即使对象Schema添加了refine等额外校验规则,shape属性依然能获取到原始的字段子Schema,比如提取description字段:
const descriptionSchema = saveHomeworkSchema.shape.description;
const result = descriptionSchema.safeParse("作业描述内容");

说明

  • shape属性是Zod对象Schema的标准属性,所有通过z.object()创建的Schema都会自带该属性,用于暴露内部各个字段的Schema定义。
  • 这种方式无需重复定义字段Schema,直接复用已有对象Schema中的配置,符合你的便捷性需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 15:52:10