使用打字稿的 formik 错误中的类型不匹配错误

111*_*110 7 typescript react-i18next formik

我有用于输入的自定义组件,formik并且在其内部渲染错误标签(如果存在)。
如果我像这样打印它:{errors[field.name]}它可以工作
但是 {t(errors[field.name]?.toLocaleString())} 这不行。

import { FieldProps, FormikErrors } from "formik";
import { useTranslation } from "react-i18next";

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>
            {errors[field.name]}
            {t(errors[field.name])} <---- this does not work
          </p>
        </div>
      )}
    </div>
  );
};

export default InputField;
Run Code Online (Sandbox Code Playgroud)

我收到错误:

Argument of type 'string | FormikErrors<any> | string[] | FormikErrors<any>[] | undefined' is not assignable to parameter of type 'TemplateStringsArray | Normalize<{test: 'test'}> | (TemplateStringsArray | Normalize<...>)[]'.
Run Code Online (Sandbox Code Playgroud)

Ro *_*ton 0

里面?errors[field.name]?.toLocaleString()意思是:“undefined如果属性toLocaleString不存在则返回errors[field.name]”。然后它尝试传递undefinedinto t(),这超出了它的定义,这就是您看到错误的原因。

但是,您可能不需要可选链接,因为您已经在上面的 4 行中检查了 property [field.name]

删除?应该修复它。尝试t(errors[field.name].toLocaleString())一下让我知道它是否有效。