-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Why Do I Need to Manually Specify Types with useField in vee-validate and Yup? #4897
-
I'm using vee-validate with Yup in a TypeScript project. To get the correct TypeScript types for my form fields, I find myself having to manually specify the type for each field like this:
import { useForm, useField } from 'vee-validate';
import * as Yup from 'yup';
const { values } = useForm({
validationSchema: Yup.object({
firstName: Yup.string().required(),
age: Yup.number().required(),
}),
});
const formFields = {
firstName: useField<(typeof values)['firstName']>('firstName'),
age: useField<(typeof values)['age']>('age'),
};
Is there a way to obtain the field types without manually specifying them for each field? What's the recommended practice for allowing vee-validate to automatically infer the types from my Yup schemas?
Beta Was this translation helpful? Give feedback.
All reactions
Replies: 1 comment 3 replies
-
With zod
you can access the pieces of the schema:
const schema = z.object({ name: z.string().min(1) }) const { value } = useField('name', toTypedSchema(schema.shape.name))
I suppose the reason you would need to be manual about it is that form values could be deep nested objects, and useField()
allows you to pass a path such as names.0.first
, so using TS inference would be a complex feat.
Beta Was this translation helpful? Give feedback.
All reactions
-
allows you to pass a path such as names.0.first, so using TS inference would be a complex feat
If that's the issue it's definitely doable. Far from being easy but doable. I got the dotted inference working but I gave up on accessing the array items: I'm pretty sure someone more knowledgeable than me could achieve it. It was easier up to a couple of years ago, but it regressed with recent versions of TS.
Beta Was this translation helpful? Give feedback.
All reactions
-
I am also not the biggest fan of how things are wired together in vee-validate ;( I guess there is a reason why I landed on this post, as I was also wondering why the heck I have to type so much code after having already typed so much code.
Beta Was this translation helpful? Give feedback.
All reactions
-
Buy the way I've also noticed a potential issue with the way the OP used validationSchema
: I usually encapsulate the whole yup object
with toTypedSchema
before passing it to validationSchema
otherwise initialValues
ends up not being type safe.
Beta Was this translation helpful? Give feedback.