简体   繁体   English

如何使模式中的所有键都不是必需的

[英]How to make all keys, from a schema, not required

I'm looking for a simple way to transform a yup schema to the same schema without any required field.我正在寻找一种简单的方法来将 yup 模式转换为相同的模式,而无需任何必填字段。

const requiredSchema = yup.object().shape({
  name: yup.string().required(),
  description: yup.string().required(),
})
// to
const notRequiredSchema = yup.object().shape({
  name: yup.string(),
  description: yup.string(),
})

I am looking for a function to apply on either requiredSchema or notRequiredSchema .我正在寻找 function 以应用于requiredSchemanotRequiredSchema The idea looks kind of like the Partial key word for types (TS) but for yup objects basically.这个想法看起来有点像类型(TS)的部分关键字,但基本上是对的对象。

Yup supports this in the 1.0.0 beta versions .是的,在1.0.0 beta 版本中支持这一点。 If you're not ok with using the beta version you could snag the code they're using to implement "partial" for object schemas.如果您不同意使用测试版,您可以获取他们用于为 object 模式实现“部分”的 代码

This is the gist of it:这是它的要点:

function partial(objectSchema) {
  const partial: any = {};
  for (const [key, schema] of Object.entries(objectSchema.fields)) {
    partial[key] =
    "optional" in schema && schema.optional instanceof Function
    ? schema.optional()
    : schema;
  }
  
  objectSchema.fields = partial

  return  objectSchema
}

The typescript seems like it might be kind of a mess to hook up if you implement it yourself.如果您自己实现 typescript,连接起来似乎有点乱。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM