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

TypeScript与react-hook-form类型不兼容:UseFormRegister赋值报错求助

解决react-hook-form传递register时的类型不匹配警告

问题原因

父组件通过useForm<AppointmentProps>生成的register类型为UseFormRegister<AppointmentProps>,但子组件AppointmentForm的props中把register定义成了默认的UseFormRegister<FieldValues>,TypeScript判定这两种类型不兼容,因此抛出警告。

解决方案

1. 修正types.ts中的AppointmentFormProps接口

给register字段指定与父组件一致的泛型类型,绑定AppointmentProps:

import { UseFormRegister } from "react-hook-form";
import { AppointmentProps } from "./types";

export interface AppointmentFormProps {
  register: UseFormRegister<AppointmentProps>;
  // 其他需要传递的props字段
}

2. 确认父组件Appointment.tsx的useForm泛型配置

保证父组件中useForm的泛型参数是AppointmentProps:

import { useForm } from "react-hook-form";
import { AppointmentProps } from "./types";
import AppointmentForm from "./AppointmentForm";

export default function Appointment() {
  const { register } = useForm<AppointmentProps>();
  
  return (
    <form>
      <AppointmentForm register={register} />
    </form>
  );
}

3. 子组件AppointmentForm.tsx正确接收props

直接使用定义好的AppointmentFormProps作为props类型:

import { AppointmentFormProps } from "./types";

export default function AppointmentForm({ register }: AppointmentFormProps) {
  return (
    <div>
      {/* 这里的fieldName必须是AppointmentProps中已定义的字段 */}
      <input {...register("fieldName")} />
    </div>
  );
}

通用化组件扩展方案

如果希望AppointmentForm支持任意表单类型,可以改为泛型组件:

// types.ts
import { UseFormRegister, FieldValues } from "react-hook-form";

export interface AppointmentFormProps<T extends FieldValues> {
  register: UseFormRegister<T>;
}

// AppointmentForm.tsx
import { AppointmentFormProps } from "./types";

export default function AppointmentForm<T extends FieldValues>({ register }: AppointmentFormProps<T>) {
  return (
    <input {...register("fieldName")} />
  );
}

// 父组件中使用时指定泛型
<AppointmentForm<AppointmentProps> register={register} />

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 22:52:03