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

use*_*289 4 javascript typescript reactjs yup formik

我正在将验证架构转换为jsx文件tsx类型。它在jsx但在tsx我无法让 yupwhen条件通过的类型中工作得很好。甚至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')
                }
            }),
Run Code Online (Sandbox Code Playgroud)

Mal*_*lio 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()
            })
Run Code Online (Sandbox Code Playgroud)

我个人更喜欢:

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()
  );
Run Code Online (Sandbox Code Playgroud)

但这只是清理。

  • 这个答案与问题不符。编辑器给出以下错误:“TS2769:没有与此调用相匹配的重载”,软件确实有字,但在编辑器上看到此错误很难看 (2认同)