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

React中useFieldArray报Type '"options"'不可赋值给never的TS错误求助

解决React Hook Form useFieldArray的TypeScript类型错误

问题场景

使用React Hook Form的useForm结合Zod构建动态表单时,useFieldArray的name参数触发类型错误:

Type '"options"' is not assignable to type 'never'.

解决方案

移除useFieldArray的手动泛型声明,让它通过form.control自动推断类型:

const form = useForm<z.infer<typeof PollValidation>>({
  resolver: zodResolver(PollValidation),
  defaultValues: {
    text: poll ? poll?.text : "",
    options: ["Option 1", "Option 2"]
  },
});

// 移除useFieldArray的泛型参数,依赖control自动推断类型
const { fields, append, remove } = useFieldArray({
  control: form.control,
  name: "options" as const,
});

原因说明

手动给useFieldArray传递表单类型泛型时,TypeScript无法自动推断合法的字段路径类型,导致路径类型默认被设为never,进而引发类型不匹配错误。而form.control已经携带了完整的表单类型信息,useFieldArray可基于此自动识别合法字段名,无需手动声明泛型。

备选方案(手动指定泛型)

若需手动声明泛型,需同时指定表单类型和字段路径类型:

const { fields, append, remove } = useFieldArray<
  z.infer<typeof PollValidation>,
  "options"
>({
  control: form.control,
  name: "options" as const,
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 04:50:07