I'm using yup with Formik in my React app which I've written in Typescript. I have the following FormikProps interface:
export interface InvoiceLevelTotal {
amount?: number;
currency?: string;
}
I've created the following ObjectSchema which I'm ultimately passing into the validationSchema property of my Formik:
const formSchema: Yup.ObjectSchema<InvoiceLevelTotal> = Yup.object().shape({
amount: Yup.number().required('Amount is required'),
currency: Yup.string().required('Currency is required')
});
As you can see, I'm attempting to type my ObjectSchema against my interface for type checking purposes, however if I change currency to currrrrrency, it does not throw a Typescript compile-time error like I would expect.
How can I strongly-type an ObjectSchema?
It looks like the code should actually be as follows:
const formSchema = Yup.object<InvoiceLevelTotal>().shape({
amount: Yup.number().required('Amount is required'),
currency: Yup.string().required('Currency is required')
});
In [email protected], I was able able to enforce the type in this way:
const formSchema = Yup.object().shape<InvoiceLevelTotal>({
amount: Yup.number().required('Amount is required'),
currency: Yup.string().required('Currency is required')
});
However, is there any way to infer a type from the schema, so that there is no need of creating the type twice. Short of like this:
const formSchema = Yup.object().shape({
amount: Yup.number().required('Amount is required'),
currency: Yup.string().required('Currency is required')
});
type InvoiceLevelTotal = typeof formSchema.[something]
@esanzgar Yep, looks like it: https://github.com/jquense/yup#typescript-support
@jedrichards thanks, that exactly what I was looking for...
@esanzgar Yep, looks like it: https://github.com/jquense/yup#typescript-support
Most helpful comment
It looks like the code should actually be as follows: