yup addMethod not working in typescript yup version

Viewed 4439

yup package

Issue

When a custom method added to yup instance using the addMethod function, It produces the error below

TS2339: Property 'title' does not exist on type 'typeof import("node_modules/yup/lib/index")'

To Reproduce

yupInstance.ts file

import * as yup from 'yup';

function defaultTitleValidation(this: any, local: 'en' | 'bn') {
  return this.string().trim().required();
}

yup.addMethod(yup.string, 'title', defaultTitleValidation);

export default yup;

common.d.ts file

declare module 'yup' {
  interface StringSchema<TIn, TContext, TOut> {
    title(local: 'en' | 'bn'): any;
  }
}

myImplementationComponent.tsx

import yup from '../../../../common/yup';

const validationSchema = yup.object().shape({
  title_en: yup.title(), // TS2339: Property 'title' does not exist on type 'typeof import("node_modules/yup/lib/index")'
});
1 Answers

Solved by extending yup.BaseSchema interface.

declare module 'yup' {
  interface StringSchema<
    TType extends Maybe<string> = string | undefined,
    TContext extends AnyObject = AnyObject,
    TOut extends TType = TType,
  > extends yup.BaseSchema<TType, TContext, TOut> {
    title(local: 'en' | 'bn'): StringSchema<TType, TContext>;
  }
}

Custom method

function defaultTitleValidation(this: any, local: 'en' | 'bn') {
  return this.trim().required(); //before this.string().trim().required();
}

Implementation

const validationSchema = yup.object().shape({
  title_en: yup.string().title('en'),  //before yup.title(),
});
Related