jquense / yup

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

Type inference for react hook form #2238

Open adenteo opened 4 months ago

adenteo commented 4 months ago

With the example code below,

    interface ITest {
        test?: string;
        test2?: string;
    }

    const testObj: yup.ObjectSchema<ITest> = yup.object().shape({
        test: yup.string().required(),
        test2: yup.string().required(),
    });

    const methods = useForm({
        mode: "onTouched",
        resolver: yupResolver(testObj),
    });

I am trying to enforce the interface ITest on testObj. However, with yup.ObjectSchema<ITest>, when i try to infer the available parameters with methods.watch(), I am unable to get them. If i remove yup.ObjectSchema<ITest>, then It works. Is there something I am doing wrong? How else do I enforce my schema type while still ensuring that I can infer the types correctly?

SCENARIO 1, WITHOUT yup.ObjectSchema<ITest>:

const testObj = yup.object().shape({
        test: yup.string().required(),
        test2: yup.string().required(),
    });
Screenshot 2024-07-28 at 10 14 24 PM Screenshot 2024-07-28 at 10 17 20 PM

SCENARIO 2, WITH yup.ObjectSchema<ITest> I lose all type inference.

const testObj: yup.ObjectSchema<ITest> = yup.object().shape({
        test: yup.string().required(),
        test2: yup.string().required(),
    });
Screenshot 2024-07-28 at 10 21 38 PM Screenshot 2024-07-28 at 10 19 31 PM

How do I achieve scenario 1 but still have the type enforcement with yup.ObjectSchema<ITest>?