同步Yup验证Schema与File类型时的TypeScript类型兼容问题
Yup验证File[]类型表单时的TypeScript类型错误解决方法
问题场景
为包含File[]类型的表单创建Yup验证Schema时,出现TypeScript类型不兼容错误,提示RequiredArraySchema与File[]类型不匹配。
原代码
type FormValues = { files: File[]; notify: string[]; }; const validationSchema = yup.object({ files: yup .array<File[]>() .of( yup .mixed<File>() .required() .test('file', 'Invalid file type', (value) => value instanceof File), ) .min(1, 'At least one file is required') .required(), notify: yup.array().of(yup.string().required()).required(), }).required(); export function UploadFileDialog() { const methods = useForm<FormValues>({ defaultValues: { files: [], notify: [], }, resolver: yupResolver<FormValues>(validationSchema), }); }
错误信息
TypeScript Error: Argument of type 'RequiredObjectSchema<{ files: RequiredArraySchema<MixedSchema<File | undefined, AnyObject, File>, AnyObject, (File | undefined)[] | undefined>; notify: RequiredArraySchema<...>; }, AnyObject, TypeOfShape<...>>' is not assignable to parameter of type 'ObjectSchema<FormValues, AnyObject, TypeOfShape<FormValues>, AssertsShape<FormValues>>'. The types of 'fields.files' are incompatible between these types. Type 'RequiredArraySchema<MixedSchema<File | undefined, AnyObject, File>, AnyObject, (File | undefined)[] | undefined>' is missing the following properties from type 'File[]': pop, push, join, reverse, and 33 more.
解决方案
错误根源有两个:
yup.array<File[]>()的泛型参数错误,应传入数组元素类型File而非数组类型File[]yup.mixed<File>()默认包含undefined类型,导致数组元素类型为File | undefined,与FormValues中的File[]不匹配
调整后的验证Schema代码:
const validationSchema = yup.object({ files: yup .array<File>() // 修正泛型参数为数组元素类型File .of( yup .mixed<File>() .defined() // 移除undefined类型,确保元素是确定的File .test('file', 'Invalid file type', (value) => value instanceof File), ) .min(1, 'At least one file is required') .required(), notify: yup.array().of(yup.string().required()).required(), }).required();
补充说明
- 使用
.defined()替代.required()可更明确地移除undefined类型,避免Schema推断类型包含可选值 - 确保array的泛型参数始终是数组元素的类型,而非数组本身,这样Schema推断类型才能与
FormValues中的File[]对齐
内容的提问来源于stack exchange,提问作者Alex Ironside
相关产品推荐
相关产品推荐

