Published 19 Jun, 2022

Reactjs - yup addMethod not working in typescript yup version

Category ReactJS
Modified : Oct 04, 2022
47

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")'
});

Answers

There are 1 suggested solutions here and each one has been listed below with a detailed description. The following topics have been covered briefly such as Javascript, Reactjs, Typescript, Next.js, Yup. These have been categorized in sections for a clear and precise explanation.

4

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(),
});

Associated Technologies

Details of all the mentioned technology in the question that you should know about for a detailed information.

Javascript

Javascript is the programming language of the web. It is client side scripting language that runs inside a browser. It's a lightweight, interpreted programming language and is very capable for network centric applications. One of the primary reasons for its popularity is also because it's fun and flexible.

Javascript is one of the core-technologies for the web alongside HTML and CSS. It is high level language with dynamic typing, first class functions and is termed as multi-paradigm as it supports event-driven, functional and imperative programming styles. It also has various APIs to work with text, dates, DOM etc.