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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With