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

react-hook-form搭配yup时赋值Yup Resolver报string索引签名缺失错误

问题原因

该报错属于TypeScript类型不匹配问题:你手动声明的IFormData接口没有字符串索引签名,和yupResolver期望的、从yup schema自动推导的带索引签名的AssertsShape类型不兼容,因此触发了2322类型错误。

可行解决方案

推荐优先使用第一种方案,类型安全性更高。

方案1:使用yup自动推导表单类型(推荐)

不需要手动声明IFormData接口,直接通过yup提供的InferType从你定义的schema中自动推导表单类型,完全避免类型不匹配问题。

修改后的核心代码如下:

import React from 'react';
import './App.css';

import TextField from '@mui/material/TextField';
import Button from '@mui/material/Button';
import { Stack, Typography } from '@mui/material';
import { useForm, SubmitHandler } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as yup from "yup";
// 导入yup的类型推导工具
import type { InferType } from 'yup';

const schema = yup.object().shape({
  srcAddress: yup.string().required("源地址不能为空"),
  tgtAddress: yup.string().required("目标地址不能为空")
});

// 直接从schema推导表单类型,无需手动写接口
type IFormData = InferType<typeof schema>;

const onSubmitHandler : SubmitHandler<IFormData> = (data:IFormData)=> {
  console.log(data);
} 

function App() {
  const {register, handleSubmit, formState: { errors } } = useForm<IFormData>({
    resolver: yupResolver(schema)
  });
  
  return (
    <div className="App">
      <form onSubmit={handleSubmit(onSubmitHandler)}>
        <Stack
          display="flex"
          justifyContent="center"
          alignItems="center"
          minHeight="100vh"
          minWidth="100vw"
          sx={{
            '& > :not(style)': { m: 1, width:"30%"},
          }}
        >
          <Typography variant="h4" sx={{textAlign:"center"}} display="inline">Money sender</Typography>
          <TextField 
            size="small" 
            label="Source Address" 
            id="srcAddress" 
            variant="standard"  
            {...register('srcAddress')}
            // 可选:添加错误提示
            error={!!errors.srcAddress}
            helperText={errors.srcAddress?.message}
          />
          <TextField 
            size="small" 
            label="Target Address" 
            variant="standard"  
            {...register('tgtAddress')}
            error={!!errors.tgtAddress}
            helperText={errors.tgtAddress?.message}
          />
          <Button variant="contained" type="submit">Send</Button>
        </Stack>
      </form>
    </div>
  );
}

export default App;

方案2:给手动声明的接口添加索引签名

如果你坚持要手动声明IFormData接口,可以给接口添加字符串索引签名兼容yup的类型要求:

interface IFormData {
  srcAddress:string,
  tgtAddress:string,
  // 添加字符串索引签名
  [key: string]: any
}
验证

修改完成后重启项目即可解决该类型报错,表单校验和提交功能均可正常运行。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 22:48:01