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

如何在Yup Schema中定义支持多类型的字段?

在Yup中定义数组元素的联合类型

你可以用Yup的mixed().oneOfType()方法实现这种数组元素的联合类型校验,这正是官方提供的多类型匹配方案。

具体实现步骤如下:

  1. 先单独定义包含必填uuid的对象Schema:
import * as yup from 'yup';

const uuidObjectSchema = yup.object().shape({
  uuid: yup.string().required('uuid字段为必填项')
});
  1. 在数组的of()方法中,用oneOfType组合你的someOtherSchema和上面的uuidObjectSchema:
const yourTargetSchema = yup.object().shape({
  field: yup.array().of(
    yup.mixed().oneOfType([
      someOtherSchema, // 你的已有Schema
      uuidObjectSchema // 刚才定义的uuid对象Schema
    ])
  )
});

这样定义后,field数组中的每个元素既可以符合someOtherSchema的结构,也可以是包含必填uuid字段的对象,两种类型都会通过校验。

如果你的两个Schema存在结构重叠(比如someOtherSchema也可能包含uuid字段),可以额外通过test方法添加自定义校验逻辑,进一步明确类型判断规则,但大多数场景下oneOfType已经足够满足需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 09:02:02