Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Why Do I Need to Manually Specify Types with useField in vee-validate and Yup? #4897

federicobartoli started this conversation in General
Discussion options

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?

You must be logged in to vote

Replies: 1 comment 3 replies

Comment options

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.

You must be logged in to vote
3 replies
Comment options

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.

Comment options

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.

Comment options

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

AltStyle によって変換されたページ (->オリジナル) /