是的。当用打字稿验证时

Yup .when validation with typescript

我正在将验证模式从 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')
                }
            }),

最简单的事情:

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

但这只是清理。