skip to Main Content

I added react hook form in react app, while validating certain fields i add some condition in schema.

yup
  .object({
    test1: yup.number().when('test2', (test2: number, schema: yup.NumberSchema): yup.NumberSchema => {
      if (test2 !== undefined && test2 < 1) {
        return schema.required('Required Field').min(0).max(100).typeError('Please enter test1')
      }
      return schema.notRequired()
    }),
    Name: yup
      .string()
      .trim()
      .required('Required Field')
      .matches(/^[A-Za-z ]+$/, 'Numbers & Special character not allowed'),
    test2: yup.number().required('Required Field').min(0).max(100).typeError('Please enter test2'),
  })
  .required(

)

TS2322: Type ‘NumberSchema<Maybe<number | undefined>, AnyObject, undefined, "">’ is not assignable to type ‘NumberSchema<number | undefined, AnyObject, undefined, "">’.
Type ‘Maybe<number | undefined>’ is not assignable to type ‘number | undefined’.
Type ‘null’ is not assignable to type ‘number | undefined’.

2

Answers


  1. try this:

    yup
      .object({
        test1: yup
          .number()
          .when('test2', (test2: number | undefined, schema: yup.NumberSchema): yup.NumberSchema => {
            if (test2 !== undefined && test2 < 1) {
              return schema.required('Required Field').min(0).max(100).typeError('Please enter test1');
            }
            return schema.notRequired();
          }),
        Name: yup
          .string()
          .trim()
          .required('Required Field')
          .matches(/^[A-Za-z ]+$/, 'Numbers & Special character not allowed'),
        test2: yup.number().required('Required Field').min(0).max(100).typeError('Please enter test2'),
      })
      .required();
    

    looks like the issue is when using the ‘when’ method as it is not compatible with the expected type

    Login or Signup to reply.
  2. If you console.log test2, you’ll see your issue – it’s an array, not a number.

    You also don’t need to explicitly declare the types because they are correctly inferred. Try this:

        test1: yup.number().when('test2', ([test2],schema) => {
            ....
        }),
    

    Notice [test2] instead of test2

    See this relevant part of the documentation:

    let schema = yup.object({
      isBig: yup.boolean(),
      count: yup.number().when('isBig', ([isBig], schema) => {
        return isBig ? schema.min(5) : schema.min(0);
      }),
    });
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search