user101289
user101289

Reputation: 10422

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

Upvotes: 4

Views: 10807

Answers (2)

Vincent Guyard
Vincent Guyard

Reputation: 414

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.

Upvotes: 0

Michael Lorton
Michael Lorton

Reputation: 44406

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.

Upvotes: 5

Related Questions