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

使用React Hook Form显示错误消息时遇TypeScript类型错误

问题原因

TypeScript报错是因为useForm未明确指定表单数据的类型,导致它无法精准推断errors对象的结构,将errors.firstName的类型判定为包含FieldError或嵌套错误对象的联合类型,而React无法直接渲染FieldError对象。

解决方法

方法1:给useForm指定泛型类型(推荐)

定义表单数据的类型,让TypeScript准确推断错误结构:

// 定义表单数据的类型
type RegisterFormData = {
  firstName: string;
  // 可添加其他字段,如lastName、email等
};

const Register = () => {
  // 给useForm传入泛型
  const { register, watch, handleSubmit, formState:{errors} } = useForm<RegisterFormData>();

  const onSubmit = handleSubmit((data)=>{
      console.log(data)
  })
  
  return (
      <form className="flex flex-col gap-5" onSubmit={onSubmit}>
          <h2 className="text-3xl">Create an account</h2>
          <div className="flex flex-col md:flex-row gap-5">
              <label className="text-gray-700 text-sm font-bold flex-1">
                  First Name
                  <input 
                    type="text" 
                    className="border border-blue-500 rounded w-full py-1 px-2 font-normal" 
                    {...register("firstName", { required: "This field is required" })} 
                  />
                  {errors.firstName && (
                   <span className="text-red-500">{errors.firstName.message}</span>
               )}
              </label>
              <span>
                  <button type="submit" className="bg-blue-600 text-white p-2 font-bold hover:bg-blue-500 text-xl">Create Account</button>
              </span>
          </div>
      </form>
  )
}

方法2:类型断言或运行时检查(快速修复)

如果暂时不想定义泛型,可通过类型断言或检查message类型消除报错:

// 类型断言
{errors.firstName && (
  <span className="text-red-500">{(errors.firstName as { message: string }).message}</span>
)}

或运行时检查确保message为字符串:

{errors.firstName && typeof errors.firstName.message === 'string' && (
  <span className="text-red-500">{errors.firstName.message}</span>
)}

额外提示

  • 原始代码存在标签未闭合问题(form、div标签未正确闭合),建议修复避免渲染异常。
  • 给useForm指定泛型是React Hook Form结合TypeScript开发的最佳实践,能在开发阶段提前捕获类型错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 15:30:08