Type missmatch error in formik errors using typescript

Viewed 1548

I have custom component for inputs for formik and inside of it I render error label if exist.
If I print it like: {errors[field.name]} it works
But {t(errors[field.name]?.toLocaleString())} this doesnt.

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;

I am getting error:

Argument of type 'string | FormikErrors<any> | string[] | FormikErrors<any>[] | undefined' is not assignable to parameter of type 'TemplateStringsArray | Normalize<{test: 'test'}> | (TemplateStringsArray | Normalize<...>)[]'.
2 Answers

The ? inside errors[field.name]?.toLocaleString() means: "return undefined if the property toLocaleString doesn't exist on errors[field.name]". Then it tries passing undefined into t(), which falls outside its definition and is why you see error .

However, you probably don't need optional chaining because 4 lines above it you are already checking for the property [field.name].

Removing the ? should fix it. Try t(errors[field.name].toLocaleString()) and let me know if it works.

Just use typeof errors[field.name] === 'string' to assure typescript that it is a string.

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

type InputFieldProps = 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] && typeof errors[field.name] === 'string' && (
        <div>
          <p>
            {errors[field.name]}
            {t(errors[field.name])}
          </p>
        </div>
      )}
    </div>
  );
};

export default InputField;

Playground

Related