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

使用对象数组时关联yup与react-hook-form字段名的问题

解决react-hook-form结合yup时数组字段注册的类型错误

尝试通过register将react-hook-form与yup的schema关联,循环渲染输入框时传入类似exampleArray${index}.exampleProp格式的字段名,遇到了类型错误。

问题代码示例

import * as yup from "yup";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";

const schema = yup.object().shape({
  exampleArr: yup.array().of(
    yup.object().shape({
      exampleProp: yup.string()
    })
  )
});

type FormValues = yup.InferType<typeof schema>;

export default function App() {
  const methods = useForm<FormValues>({
    resolver: yupResolver(schema)
  });
  return (
    <input type="text" {...methods.register("exampleArr[0].exampleProp")} /> // 此处报错
  );
}

错误提示

类型为'"exampleArr[0].exampleProp"'的参数无法赋值给类型为'"exampleArr" | exampleArr.${number} | exampleArr.${number}.exampleProp'的参数。


解决方案

  1. 改用点语法的索引格式
    react-hook-form的TypeScript类型系统更认可exampleArr.0.exampleProp这种点连接索引的写法,替换方括号写法即可解决类型错误:
<input type="text" {...methods.register("exampleArr.0.exampleProp")} />
  1. 循环渲染时动态生成字段名
    如果是循环生成输入框,直接用模板字符串拼接成正确格式:
{[0, 1, 2].map(index => (
  <input 
    key={index} 
    type="text" 
    {...methods.register(`exampleArr.${index}.exampleProp`)} 
  />
))}
  1. 复杂场景用Controller组件
    如果遇到多层嵌套数组等复杂场景,使用Controller组件也能规避类型问题:
import { Controller } from "react-hook-form";

// ...

<Controller
  name={`exampleArr.${index}.exampleProp`}
  control={methods.control}
  render={({ field }) => <input type="text" {...field} />}
/>

原因说明

react-hook-form的类型推导逻辑中,数组字段的合法路径格式是用点连接索引(如exampleArr.0.exampleProp),而方括号写法(exampleArr[0].exampleProp)虽然运行时有效,但TypeScript无法将其识别为符合定义的字段路径,因此抛出类型错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 02:44:54