Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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')
                }
            }),
like image 378
user101289 Avatar asked Oct 18 '25 03:10

user101289


2 Answers

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.

like image 71
Michael Lorton Avatar answered Oct 20 '25 17:10

Michael Lorton


The reason Typescript show you this error is because you didn't specified the return type.

.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; }
})

In this example, input and output schema are typed with NumberSchema. PD: You have to use schema parameter to sum adicional validations.

like image 20
Vincent Guyard Avatar answered Oct 20 '25 17:10

Vincent Guyard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!