You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Yup、vee-validate与TypeScript校验对象数组出现TS错误如何解决

问题原因

该TypeScript错误本质是useForm未显式关联表单字段的类型定义,导致Yup校验规则和你声明的RoleType接口无法匹配,同时未标记必填的Yup字段会被自动推导为可选类型,也会和全必填的RoleType产生类型冲突。

修复步骤

  1. 给useForm添加泛型约束,指定表单的字段类型
const { handleSubmit, errors, meta, setValues } = useForm<{ roles: RoleType[] }>({
  validationSchema,
});
  1. 补全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'),
});
  1. 如果你的业务场景里RoleType的字段确实是可选的,不需要加required(),只需要调整RoleType的字段定义为可选即可:
export interface RoleType {
  id?: number;
  title?: string;
  created_at?: string;
  updated_at?: string;
}

内容的提问来源于stack exchange,提问作者ShaSha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 12:18:03