TypeScript下Formik翻译errors对象时出现类型不匹配错误
报错原因
Formik 中 errors[field.name] 的类型为联合类型 string | FormikErrors<any> | string[] | FormikErrors<any>[] | undefined,而 react-i18next 的 t() 函数要求入参必须为字符串类型的翻译key,二者类型不匹配,因此触发TypeScript报错。
解决方法
你只需要对 errors[field.name] 做类型收窄,确保传入 t() 的参数是字符串类型即可,两种常用写法如下:
- 写法1:类型判断(更安全,兼容嵌套错误/数组错误场景)
{touched[field.name] && errors[field.name] && ( <div> <p> {typeof errors[field.name] === 'string' ? t(errors[field.name]) : errors[field.name]} </p> </div> )}
- 写法2:类型断言(适用于确定当前字段错误一定为字符串的业务场景,写法更简洁)
{touched[field.name] && errors[field.name] && ( <div> <p> {t(errors[field.name] as string)} </p> </div> )}
注意:请提前在你的i18n翻译资源文件中配置好对应错误文案的key,否则翻译函数会直接返回key本身而非翻译后的内容。
修改后的完整组件代码参考:
import { FieldProps, FormikErrors } from "formik"; import { useTranslation } from "react-i18next"; // 补充原代码缺失的InputFieldProps类型定义 interface InputFieldProps { type: string; label: string; [key: string]: any; } const InputField: React.FC<InputFieldProps & FieldProps> = ({ field, form: { touched, errors }, type, label, ...props }) => { const { t } = useTranslation(); return ( <div> <label htmlFor={field.name}> {label} </label> <input type={type} {...field} {...props}/> {touched[field.name] && errors[field.name] && ( <div> <p> {typeof errors[field.name] === 'string' ? t(errors[field.name]) : errors[field.name]} </p> </div> )} </div> ); }; export default InputField;
内容的提问来源于stack exchange,提问作者1110
相关产品推荐
相关产品推荐

