Search code examples
javascriptreactjstypescriptformikyup

Yup .when validation with typescript


I'm converting a validation schema from jsx to a tsx filetype. It works perfectly in jsx but in tsx I can't get the type for the yup when condition to pass. Even any fails to pass. Any idea how to type this correctly? The error appearing is

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

My validation:

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')
                }
            }),

Solution

  • Simplest thing:

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

    Personally I would prefer:

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

    but that is just clean up.