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

TypeScript中react-hook-form传handleSubmit报类型错误如何解决

报错原因

调用useForm时未显式传入表单值的类型泛型,TypeScript无法识别表单提交返回的数据结构,默认将提交值推导为宽泛的{ [x: string]: any }类型,和你定义的signUpCredentials接口结构不匹配,触发类型校验错误。

修复方法

在调用useForm时,将表单数据类型作为泛型参数传入,明确告知TS表单提交值的结构即可:

// TS接口建议遵循大驼峰命名规范
interface SignUpCredentials {
  name: string 
  email: string
  password: string 
  address: {
    zipCode: string 
    number: number 
    complement: string 
  } 
}

const {
  register,
  formState: { errors },
  handleSubmit,
} = useForm<SignUpCredentials>({
  resolver: yupResolver(schema)
})

修改后onSubmit={handleSubmit(handleSignup)}的类型校验会直接通过,不会再报类型不兼容错误。

可选优化

你当前写的yup校验规则没有添加必填约束,空内容也能通过校验,如果业务要求字段必填,记得补上.required()校验。另外可以直接通过yup的InferType从校验schema自动推导表单类型,不用重复写interface,避免后续schema和类型定义不同步:

const schema = yup.object().shape({
  name: yup.string().required("请输入姓名"), 
  email: yup.string().email("请输入有效邮箱").required("请输入邮箱"),
  password: yup.string().required("请输入密码"),
  address: yup.object().shape({
    zipCode: yup.string().required("请输入邮编"),
    number: yup.number().required("请输入门牌号").typeError("门牌号必须为数字"),
    complement: yup.string(),
  })
})
// 直接从schema推导表单类型
type SignUpCredentials = yup.InferType<typeof schema>;

注意address.number是数字类型,必须加上.typeError()自定义错误提示,否则输入非数字内容时,yup会抛出默认的晦涩类型错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 02:21:18