jquense / yup

Dead simple Object schema validation
MIT License
22.94k stars 935 forks source link

addMethod-ed to `mixed` is not available on all others (i.e. `string`, `number`, etc) #2058

Closed csantos-nydig closed 1 year ago

csantos-nydig commented 1 year ago

before v1.x I was able to add a method to mixed and this method would be available to all helpers (i.e. string, number, date, etc)

addMethod(mixed, "forAll", function forAll() {
  return this.transform(() => {
    return "just for testing";
  });
});

To Reproduce

Expected behavior

Platform (please complete the following information):

jquense commented 1 year ago

correct, mixed is not the base schema in v1, please add your method to Schema according to the docs

csantos-nydig commented 1 year ago

@jquense thanks for the quick answer

addMethod(Schema, "forAll", function forAll() {
  return this.transform(() => {
    return "just for testing";
  });
});

It works in Javascript but it fails TypeScript, see the updated codesandox: https://codesandbox.io/s/mixed-yup1-0-2-forked-l56m8r

jquense commented 1 year ago

You also need to extend the type correctly, including the generics

csantos-nydig commented 1 year ago

You also need to extend the type correctly, including the generics

Where can I find this in the documentation? Sorry to keep bothering you. I see https://github.com/jquense/yup#extending-built-in-schema-with-new-methods which only covers string not Schema. plus this is for when I want to use my added method, not for calling addMethod per-se.


I'm not sure you looked at the codesandbox.io/s/mixed-yup1-0-2-forked-l56m8r, but let me add an image here to show you where the TypeScript errors shows up:

Screenshot 2023-07-17 at 8 35 04 AM

I also cloned yup repository locally, and pasted in my code in one of the ts files: the typescript error is the same

image

I see you have unit tests for addMethod https://github.com/jquense/yup/blob/master/test/yup.js#L206-L211, but that file is written in JavaScript, so the TypeScript error doesn't show up

but the TS error appears if you move this simple line from .js to .ts:

addMethod(Schema, 'foo', () => 'here');
image

I don't think it has anything to do with the declare statement, which is actually working: see the green box in the screenshot above, and it also works fine when executed.

image

So the TS error is when calling addMethod on Schema not when using the added method. 👇

image