【问题标题】:Type 'undefined' is not assignable to type 'Schema<unknown>'. Yup类型“未定义”不可分配给类型“架构<未知>”。是的
【发布时间】:2020-05-14 03:08:57
【问题描述】:

我不确定我是否收到此错误,有人知道如何解决这个问题吗? 下面是我的代码,错误发生在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' 的参数。 键入“对象架构> | undefined' 不可分配给类型 'Schema'。 类型“未定义”不可分配给类型“架构”。

【问题讨论】:

    标签: react-native formik yup


    【解决方案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 和那个错误。

    我不确定您需要退回什么,但它一定是什么。

    【讨论】:

      【解决方案2】:

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

      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(),
              });
            }
          }
        }),
      ),
      

      我通过像这样为“额外”设置架构来解决这个问题。

      【讨论】:

      • 谢谢,这很有魅力
      猜你喜欢
      • 2021-02-28
      • 2021-07-02
      • 1970-01-01
      • 2021-04-29
      • 2022-01-07
      • 2020-11-02
      • 2021-08-30
      • 2021-10-19
      • 1970-01-01
      相关资源
      最近更新 更多