是的 addMethod 无法在打字稿中工作 是的版本

Bak*_*san 5 javascript typescript reactjs next.js yup

是的,包

问题

当使用 addMethod 函数将自定义方法添加到 yup 实例时,会产生以下错误

TS2339:类型“typeof import("node_modules/yup/lib/index")”上不存在属性“title”

重现

yupInstance.ts 文件

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;
Run Code Online (Sandbox Code Playgroud)

common.d.ts 文件

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

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")'
});
Run Code Online (Sandbox Code Playgroud)

Bak*_*san 7

通过扩展接口解决yup.BaseSchema

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>;
  }
}
Run Code Online (Sandbox Code Playgroud)

定制方法

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

执行

const validationSchema = yup.object().shape({
  title_en: yup.string().title('en'),  //before yup.title(),
});
Run Code Online (Sandbox Code Playgroud)