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

React Hook Form的register函数出现TypeScript类型参数无法推断错误

React Hook Form + TypeScript:修复register函数“Type argument cannot be inferred from usage”错误

你的代码出现这个类型推断错误,核心原因是TypeScript无法通过现有代码链明确推断出register函数关联的表单字段类型,常见的修复方式有两种:

方法一:给onSubmit函数明确指定参数类型

给onSubmit的参数加上你定义的LoginForm类型,让TypeScript能反向关联表单字段的类型信息:

import { useForm } from "react-hook-form";

type LoginForm = {
    email: string;
    password: string;
}

export const Login = () => {
    const { register, handleSubmit, watch, formState: { errors } } = useForm<LoginForm>();
    // 明确指定data的类型为LoginForm
    const onSubmit = (data: LoginForm) => console.log(data);

    return (
        <form onSubmit={handleSubmit(onSubmit)}>
            <input defaultValue="test" {...register("email")} />
            <input {...register("password", { required: true })} />
            {errors.password && <span>This field is required</span>}
            <input type="submit" />
        </form>
    );
}

方法二:给useForm添加defaultValues配置

通过提供表单默认值,帮助React Hook Form的类型系统更清晰地推断字段类型:

import { useForm } from "react-hook-form";

type LoginForm = {
    email: string;
    password: string;
}

export const Login = () => {
    // 添加defaultValues配置
    const { register, handleSubmit, watch, formState: { errors } } = useForm<LoginForm>({
        defaultValues: {
            email: "",
            password: ""
        }
    });
    const onSubmit = data => console.log(data);

    return (
        <form onSubmit={handleSubmit(onSubmit)}>
            <input defaultValue="test" {...register("email")} />
            <input {...register("password", { required: true })} />
            {errors.password && <span>This field is required</span>}
            <input type="submit" />
        </form>
    );
}

额外注意

确保你的React Hook Form版本(建议v7+)和TypeScript版本(建议4.3+)兼容,过低的版本也可能导致类型推断异常。

内容的提问来源于stack exchange,提问作者Wai Yan Hein

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 11:38:07