是的。当使用打字稿进行验证时

问题描述 投票:0回答:2

我正在将验证模式从

jsx
转换为
tsx
文件类型。它在
jsx
中工作得很好,但在
tsx
中我无法让 yup
when
条件通过的类型。连
any
都未能通过。知道如何正确输入吗? 出现的错误是

Argument of type '(startTime: Date) => Yup.DateSchema<Date | undefined, Record<string, any>, Date | undefined> | undefined' is not assignable to parameter of type 'ConditionOptions<RequiredDateSchema<Date | undefined, Record<string, any>>>'.

Type '(startTime: Date) => Yup.DateSchema<Date | undefined, Record<string, any>, Date | undefined> | undefined' is not assignable to type 'ConditionBuilder<RequiredDateSchema<Date | undefined, Record<string, any>>>'.

Type 'DateSchema<Date | undefined, Record<string, any>, Date | undefined> | undefined' is not assignable to type 'SchemaLike'. Type 'undefined' is not assignable to type 'SchemaLike'.  TS2345

我的验证:

Yup.date().required('This field is required')
            .when('startTime', (startTime: Date) => { // <-- this is where error appears
                if (startTime) {
                    return Yup.date()
                        .min(startTime, 'End must be after Start')
                        .typeError('End is required')
                }
            }),
javascript reactjs typescript formik yup
2个回答
5
投票

最简单的事情:

Yup.date().required('This field is required')
            .when('startTime', (startTime: Date) => {
                if (startTime) {
                    return Yup.date()
                        .min(startTime, 'End must be after Start')
                        .typeError('End is required')
                } 
                return Yup.date()
            })

我个人更喜欢:

Yup.date()
  .required("This field is required")
  .when("startTime", (startTime) =>
    startTime
      ? Yup.date()
          .min(startTime, "End must be after Start")
          .typeError("End is required")
      : Yup.date()
  );

但这只是清理而已。


0
投票

Typescript 向您显示此错误的原因是因为您没有指定返回类型。

.when('x_lifetime_type', (values: string[], schema: NumberSchema): NumberSchema => {
  if (values.indexOf('seconds') >= 0) {
     return schema.min(60, 'Minimum value is 1 minute');
  } else { return schema; }
})

在此示例中,输入和输出模式使用

NumberSchema
键入。 PD:您必须使用
schema
参数来总结附加验证。

© www.soinside.com 2019 - 2024. All rights reserved.