jquense / yup

Dead simple Object schema validation
MIT License
22.93k stars 934 forks source link

How to use addMethod with typescript #2228

Closed miyaogenta closed 4 months ago

miyaogenta commented 4 months ago

・code

declare module "yup" {
  interface MixedSchema {
    maxMBSize(mb: number): MixedSchema;
  }
}

yup.addMethod<yup.MixedSchema>(yup.mixed, "maxMBSize", function (mb: number) {
  return this.test({
    name: "maxMBSize",
    message: ({ label }: { label: string }) =>
      `The total size of ${label} must be less than ${mb}MB`,

    test: (files: FileList): boolean => {
      Array.from(files).forEach((file: File) => console.log(file));
      const totalSize = Array.from(files).reduce(
        (size, file) => size + file.size,
        0
      );
      return totalSize < mb * 1024 * 1014;
    },
  });
});

・error

No overload matches this call.
  Overload 1 of 4, '(options: TestConfig<AnyPresentValue | undefined, AnyObject>): MixedSchema<AnyPresentValue | undefined, AnyObject, undefined, "">', gave the following error.
    Type '(files: FileList) => boolean' is not assignable to type 'TestFunction<AnyPresentValue | undefined, AnyObject>'.
      Types of parameters 'files' and 'value' are incompatible.
        Type 'AnyPresentValue | undefined' is not assignable to type 'FileList'.
          Type 'undefined' is not assignable to type 'FileList'.
  Overload 2 of 4, '(test: TestFunction<AnyPresentValue | undefined, AnyObject>): MixedSchema<AnyPresentValue | undefined, AnyObject, undefined, "">', gave the following error.
    Object literal may only specify known properties, and 'name' does not exist in type 'TestFunction<AnyPresentValue | undefined, AnyObject>'.ts(2769)
index.d.ts(66, 5): The expected type comes from property 'test' which is declared here on type 'TestConfig<AnyPresentValue | undefined, AnyObject>'
jquense commented 4 months ago

This is in the docs: https://github.com/jquense/yup?tab=readme-ov-file#extending-built-in-schema-with-new-methods