Trouble declaring a string array in a yup schema

21 views Asked by At

I have a form that contains a multi select, so I have the following type definition:

export type Fields = {
    spokenLanguages: string[];
    // other fields
};

Then I define a yup schema for the array as described in their docs:

export const FieldsSchema = yup.object({
    spokenLanguages: yup.array(yup.string()).required("This field is required"),
    // other fields
});

I have also tried with array().of(yup.string())

When I add the validation to my (react-hook-form) form, I get:

Type '{ spokenLanguages: (string | undefined)[]; }' is not assignable to type 'Fields' (which is string[])

I thought it would be a common question since it is a normal string array, but I have searched far and wide with no luck.

If I just declare the array and not the type of it, the error disappears:

yup.array().required("This field is required")

but shouldn't I declare the type of the array? Furthermore if I make the string type required, the error disappears, but I am not sure what it actually means.

array().of(yup.string().required()).required("Required")

If you want to see where I declare the schema validation:

const { register } = useForm<Fields>({
    resolver: yupResolver(FieldsSchema),
});
0

There are 0 answers