React Hook Form类型报错:Merge类型无法赋值给FieldError
问题分析与解决方案
问题根源
你的SignUpCredentials接口中,属性类型误用了大写的String(JavaScript构造函数类型),而非TypeScript的基本类型string。react-hook-form在处理这类对象类型字段时,会将String的原型方法(如toString、charAt等)合并到错误对象中,导致errors.username这类错误的类型变为Merge<FieldError, ...>,与TextInputField组件定义的FieldError类型不兼容,从而触发编译错误。
修复步骤
1. 修正SignUpCredentials接口类型
将接口内所有String替换为TypeScript标准基本类型string:
export interface SignUpCredentials{ username: string, email: string, password: string, }
2. 可选:优化TextInputField组件的类型安全性
避免使用UseFormRegister<any>,改成泛型组件,让表单字段类型更严谨:
import { Form } from "react-bootstrap"; import { FieldError, RegisterOptions, UseFormRegister } from "react-hook-form"; // 泛型接口,支持传入表单数据类型 interface TextInputFieldProps<T> { name: keyof T; label: string; register: UseFormRegister<T>; registerOptions?: RegisterOptions<T>; error?: FieldError; [x: string]: any; } // 泛型组件实现 const TextInputField = <T extends object>({name, label, register, registerOptions, error, ...props}: TextInputFieldProps<T>) => { return ( <Form.Group className="mb-3" controlId={`${name}-input`} > <Form.Label> {label} </Form.Label> <Form.Control {...props} {...register(name as string, registerOptions)} isInvalid={!!error} /> <Form.Control.Feedback type="invalid"> {error?.message} </Form.Control.Feedback> </Form.Group> ); } export default TextInputField;
3. 可选:调用组件时指定泛型
如果做了第二步的泛型优化,在SignUpModal中调用时指定类型,获得更精准的类型提示:
<TextInputField<SignUpCredentials> name="username" label="Username" type="text" placeholder="Username" register={register} registerOptions={{ required: "Required" }} error={errors.username} />
为什么其他调用场景无编译错误?
其他场景要么使用了string基本类型,要么表单数据类型设为any,react-hook-form不会触发原型方法合并的类型问题,因此未报错。
内容的提问来源于stack exchange,提问作者Prasath S
相关产品推荐
相关产品推荐

