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

React Hook Form中传递useForm的errors与register的类型定义

React Hook Form中register与errors的正确类型定义

问题描述

在使用React Hook Form的useForm Hook时,需要将获取到的register和errors传递给子组件,但当前定义的接口中这两个属性都使用了any类型,希望替换为正确的类型。相关代码如下:

父组件中useForm的使用

const {
    register,
    handleSubmit,
    watch,
    control,
    formState: { errors, isDirty, isValid }
  } = useForm<CampaignForm>({
    mode: 'all',
    resolver: yupResolver(validationSchema),
    defaultValues: {
      [FormFields.StartDate]: null,
      [FormFields.EndDate]: null,
      [FormFields.StartTime]: null,
      [FormFields.EndTime]: null,
      [FormFields.Locations]: `${strings.campaign.createCampaign.allRetailLocation}`
    }
  })

子组件调用

<Campaigon erros={errors} register={register}/>

当前的子组件接口定义

interface ICampaign {
  register: any
  errors: any
}

解决方案

React Hook Form内置了专门的类型工具,可以基于你的表单类型CampaignForm来精准定义这两个属性的类型:

1. 导入所需类型

首先从react-hook-form中导入对应的类型:

import { UseFormRegister, FieldErrors } from 'react-hook-form';

2. 修改子组件接口

将ICampaign接口中的any替换为对应的类型:

interface ICampaign {
  register: UseFormRegister<CampaignForm>;
  errors: FieldErrors<CampaignForm>;
}

说明

  • UseFormRegister<CampaignForm>:专门描述register函数的类型,会根据CampaignForm的结构提供完整的类型校验和自动提示。
  • FieldErrors<CampaignForm>:对应表单错误对象的类型,会匹配CampaignForm中每个字段可能存在的错误结构,避免类型不匹配的问题。

这样定义后,TypeScript会在你使用register和errors时提供准确的类型检查,消除any带来的类型安全隐患。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 04:15:48