Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom validation method in Yup throws TypeScript error

I'm a little new to TypeScript and still don't know enough about a few things. I'm adding a custom validation method in Yup. like this:

yup.addMethod(yup.string, 'noOnlyWhitespace', function noOnlyWhitespace() {
  return this.transform((value: string, originalValue: string) =>
    /\s/.test(originalValue) ? '' : value,
  );
});

it checks if the user has entered only white spaces in the input field. Now I'm adding the validation like this:

const schema = yup
  .object()
  .shape({
    address1: yup.string().required().noOnlyWhitespace(),
  })

Now, TypeScript complains about the custom method:

Property 'noOnlyWHitespace' does not exist on type 'RequiredStringSchema<...>.

So I added a type decleration:


declare module 'yup' {
  interface RequiredStringSchema {
    noOnlyWhitespace(): string;
  }
}

it solves the error, but now it complains about the rest of the yup mehtods not existing. for example(for yup.string):

Property 'string' doesn not exist on type 'typeof import("yup")'.

Please let me know what's the best solution here.

like image 423
Bharat Soni Avatar asked Sep 11 '25 14:09

Bharat Soni


1 Answers

I have never uploaded an answer before, please be patient on me haha.

The rest of methods no longer exist, because you overwrote the base types. You have to declare your module, extending the base types in your declaration file.

Here's a working example with your code:

import * as Yup from 'Yup';

declare module 'yup' {
  interface StringSchema extends Yup.StringSchema {
    noOnlyWhitespace(): StringSchema;
  }
}

The StringSchema in the end uses a pattern to keep returning StringSchema functions.

like image 147
Juan Carlos Tremols Avatar answered Sep 13 '25 02:09

Juan Carlos Tremols