使用Yup、vee-validate与TypeScript校验对象数组出现TS错误如何解决
问题原因
该TypeScript错误本质是useForm未显式关联表单字段的类型定义,导致Yup校验规则和你声明的RoleType接口无法匹配,同时未标记必填的Yup字段会被自动推导为可选类型,也会和全必填的RoleType产生类型冲突。
修复步骤
- 给
useForm添加泛型约束,指定表单的字段类型
const { handleSubmit, errors, meta, setValues } = useForm<{ roles: RoleType[] }>({ validationSchema, });
- 补全Yup schema的必填校验,同时可以直接用Yup推导类型,避免重复定义
RoleType(可选,推荐)
import { InferType } from 'yup'; // 抽离单个role的校验规则 const roleSchema = yup.object().shape({ id: yup.number().required(), title: yup.string().required(), created_at: yup.string().required(), updated_at: yup.string().required(), }); // 直接从schema推导类型,不需要单独写interface,保证schema和类型永远一致 export type RoleType = InferType<typeof roleSchema>; const validationSchema = yup.object({ roles: yup.array().of(roleSchema).required('Role is required'), });
- 如果你的业务场景里
RoleType的字段确实是可选的,不需要加required(),只需要调整RoleType的字段定义为可选即可:
export interface RoleType { id?: number; title?: string; created_at?: string; updated_at?: string; }
内容的提问来源于stack exchange,提问作者ShaSha
相关产品推荐
相关产品推荐

