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

如何将Yup对象Schema所有字段转为非必填?实现TS Partial类似功能

实现类似TypeScript Partial的Yup Schema转换函数

基础版(处理平级字段)

如果你只需要处理平级的对象Schema,可以用这个简单函数,遍历所有字段并移除必填约束:

function partialYupSchema(schema) {
  if (!schema.isObjectSchema) {
    throw new Error('仅支持Yup对象类型Schema');
  }

  const partialFields = Object.fromEntries(
    Object.entries(schema.fields).map(([key, fieldSchema]) => [
      key,
      fieldSchema.notRequired()
    ])
  );

  return yup.object().shape(partialFields);
}

递归版(支持嵌套对象)

如果你的Schema包含嵌套的对象字段,需要递归处理每个层级的字段,确保所有嵌套字段也转为非必填:

function partialYupSchema(schema) {
  // 递归处理嵌套对象Schema
  if (schema.isObjectSchema) {
    const partialFields = Object.fromEntries(
      Object.entries(schema.fields).map(([key, fieldSchema]) => [
        key,
        partialYupSchema(fieldSchema)
      ])
    );
    return yup.object().shape(partialFields).notRequired();
  }

  // 非对象字段直接移除必填约束
  return schema.notRequired();
}

使用示例

用你提供的测试场景验证:

const requiredSchema = yup.object().shape({
  name: yup.string().required(),
  description: yup.string().required(),
  // 嵌套对象示例(仅递归版支持)
  nested: yup.object().shape({
    age: yup.number().required()
  })
});

// 转换为全非必填Schema
const notRequiredSchema = partialYupSchema(requiredSchema);

// 验证效果:所有字段(包括nested.age)都不再是必填项
notRequiredSchema.validate({}).then(valid => console.log(valid)); // 输出{},无报错

注意事项

  • 调用notRequired()是幂等的,即使原字段已经是非必填,重复调用也不会产生问题,所以这个函数可以安全地应用于已转换过的Schema。
  • 如果需要保留特定字段的必填性,可以修改函数,比如传入一个例外字段数组,遍历的时候跳过这些字段的notRequired()调用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 02:55:14