类型'undefined'不能分配给类型'Schema <unknown>'。是的

时间:2020-05-14 03:08:57

标签: react-native formik yup

我不确定是否收到此错误,有人知道如何解决吗? 以下是我的代码,错误发生在extra: Yup.array().of(Yup.lazy((value)....

const claimFormValidationSchema = Yup.object().shape<ClaimApplicationForm>({
  id: Yup.number().notRequired(),
  claimType: Yup.mixed().required(),
  claimAmount: Yup.number().required('Claim Amount is Required'),
  currencyCode: Yup.string().required(),
  rate: Yup.number().required('Rate is Required'),
  convertedAmount: Yup.number().required('Converted Amount is Required'),
  extra: Yup.array().of(
    Yup.lazy((value) => {
      if ('required' in value) {
        if (value.required === true) {
          return Yup.object().shape({
            value: Yup.string().required(),
          });
        } else {
          return Yup.object().shape({
            value: Yup.string().notRequired(),
          });
        }
      }
    }),
  ),
});

错误:

类型'(值:未知)=> ObjectSchema>的参数undefined'不能分配给'(value:unknown)=> Schema'类型的参数。 输入'ObjectSchema> |未定义”不能分配给“模式”类型。 类型'undefined'不能分配给类型'Schema'。

2 个答案:

答案 0 :(得分:1)

您的问题出在extra属性

  extra: Yup.array().of(
    Yup.lazy((value) => {
      // outter if
      if ('required' in value) {
        if (value.required === true) {
          return Yup.object().shape({
            value: Yup.string().required(),
          });
        } else {
          return Yup.object().shape({
            value: Yup.string().notRequired(),
          });
        }
      }          
      // end outter if

      // if reaches here, nothing is returned
    }),
  ),

您需要在Yup.lazy内返回内容,但是如果'required' in value的条件不成立,您将不会返回任何内容,从而给您undefined和该错误。

我不确定您需要退货什么,但这一定是东西。

答案 1 :(得分:0)

一段时间后,我得到了我期望做的。

extra: Yup.array().of(
  Yup.lazy((data: any) => {
    if ('required' in data) {
      if (data.required === true) {
        return Yup.object().shape({
          value: Yup.string().required(),
        });
      } else {
        return Yup.object().shape({
          value: Yup.string().notRequired(),
        });
      }
    }
  }),
),

我通过为“额外”设置架构来解决此问题。