Error message: "Mismatched data types in Formik errors when utilizing TypeScript"

I have a customized input component for formik which includes an error label if one exists.
When I print it like this: {errors[field.name]}, it works.
However, {t(errors[field.name]?.toLocaleString())} does not work.

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

const CustomInput: React.FC<CustomInputProps & 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 CustomInput;

I am encountering this error:

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

Answer №1

I encountered a similar issue and was able to resolve it by using Formik with the Material-UI library:

 {errors?.fieldName && typeof errors.fieldName=== "string" && (
                    <Typography component={'div'} fontSize={12} color={'red'}>
                      {errors.fieldName}
                    </Typography>)}

Answer №2

Encountered a problem while using useFormik(), but managed to handle the error in a secure manner

{formik.errors.fieldName ? <span>{formik.errors.fieldName as string}</span> : null}

Answer №3

The ? used in

errors[field.name]?.toLocaleString()
indicates that if the property toLocaleString does not exist on errors[field.name], it will return undefined. As a result, passing undefined into t() leads to an error 😉.

However, considering that you are already checking for the property [field.name] four lines above, using optional chaining may be unnecessary.

Removing the ? should resolve the issue. You could try using

t(errors[field.name].toLocaleString())
and see if that works instead.

Answer №4

To ensure TypeScript recognizes it as a string, simply use

typeof errors[field.name] === '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

Answer №5

Dealing with this typescript error can be approached in various ways.

We have the option to utilize as string or String(errors.email) in this manner:

{errors?.email && touched?.email && (
        <div className="text-red-500 mt-3">
             {errors?.email as string}
        </div>
)}
{errors?.email && touched?.email && (
        <div className="text-red-500 mt-3">
             {String(errors?.email)}
        </div>
)}

Alternatively, we can make use of the <ErrorMessage /> component from Formik:

import { ErrorMessage } from 'formik';

   <ErrorMessage name="email" />

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing dynamic value changes in MUI Select using Formik's onChange event

Integrating the Formik with the Select component of MUI presented me with a few obstacles. Initially, it failed to update the value on the onChange event and did not display any error messages when nothing was selected. After some troubleshooting, I was ...

There seems to be an issue with calling this particular expression. The elements within the type 'string | ((searchTerm: string) => Promise<void>) | []' are not all callable

Here is my unique useResults custom hook: import { useEffect, useState } from 'react'; import yelp from '../api/yelp'; export default () => { const [results, setResults] = useState([]); const [errorMessage, setErrorMessage] = us ...

Could anyone provide an explanation for the statement "What does '[P in keyof O]: O[P];' signify?"

As a new Typescript user looking to build a passport strategy, I came across a line of code that has me completely baffled. The snippet is as follows: here. The type StrategyCreated<T, O = T & StrategyCreatedStatic> = { [P in keyof O]: O[P]; ...

What is the best way to create a generic function parameter for a single property of an object?

I am trying to refactor a generic function into accepting parameters as a single object function test<T>(a: string, b: T, c: number) Instead, I want the function to receive an object like this: function test(params: {a: string; b: T, c: number}) I ...

What could be causing the issue with Vite build and npm serve not functioning together?

After shifting from CRA to VITE, I am encountering a problem with serving my app. I successfully build my app using vite build. and can serve it using Vite serve without any issues. However, I want to use npm's serve command. Whenever I run vite bui ...

Material UI Error TS1128: Expected declaration or statement for ButtonUnstyledProps

While working on my application that utilizes Material UI, I encountered an issue. I keep receiving a Typescript error and haven't been able to find a solution for it. TypeScript error in C:/.../node_modules/@mui/base/ButtonUnstyled/index.d.ts(3,1): D ...

The type 'Requireable<string>' cannot be matched with the type 'Validator<"horizontal" | "vertical" | undefined>'

code import * as React from 'react'; import * as PropTypes from 'prop-types'; interface ILayoutProps { dir?: 'horizontal' | 'vertical' }; const Layout: React.FunctionComponent<ILayoutProps> = (props) => ...

Bar chart in Chart.js becomes crowded and illegible on smaller screens due to overlapping bars

Hello there! I've encountered an issue where the bar chart overlaps when the screen width is too low. It seems to be related to the maintainAspectRatio property, which I set to false because I wanted the charts to shrink only in width, not in both axe ...

Next JS now includes the option to add the async attribute when generating a list of script files

We are currently working on a nextJs application and are looking to add asynchronous functionality to all existing script tags. Despite numerous attempts, we haven't been successful in achieving this. Can anyone provide some guidance or assistance? &l ...

How can you incorporate TypeScript's dictionary type within a Mongoose schema?

When using TypeScript, the dictionary type format is: { [key: string]: string; } However, when I try to define a custom schema in mongoose, it doesn't work as expected. const users = new Schema({ [key: string]: String, }); I also attempted t ...

What is a way to execute a series of requests using rxjs similar to forkJoin and combineLatest, without needing to wait for all requests to finish before viewing the results?

Consider you have a list of web addresses: urls: string[] You create a set of requests (in this instance, utilizing Angular's HTTPClient.get which gives back an Observable) const requests = urls.map((url, index) => this.http.get<Film>(url) ...

Having issues with @ts-ignore in Typescript on a let variable that is not reassigned?

JOURNEY TO THE PROBLEM My current task involves destructuring a response obtained from an Apollo useLazyQuery, with the intention to modify one variable. In a non-Typescript environment, achieving this would be straightforward with just two lines of code: ...

Tips for setting ngModel and name attributes in an angular test for a custom component

Just getting started with angular. I recently developed a custom component that implements the ControlValueAccessor to allow developers to easily access its value. Here's an example of how it can be used: <app-date [label]="'Date 2&apos ...

Decorators do not allow function calls, yet the call to 'CountdownTimerModule' was executed

While building production files, the aot process is failing with this error message: Function calls are not supported in decorators but 'CountdownTimerModule' was called. I run the build command using npm run build -- --prod --aot and encounter ...

There are no HTTP methods available in the specified file path. Make sure to export a distinct named export for each HTTP method

Every time I attempt to run any code, I encounter the following error message: No HTTP methods exported in 'file path'. Export a named export for each HTTP method. Below is the content of my route.ts file: import type { NextApiRequest, NextApi ...

What is a Mongoose Schema type in TypeScript and how can it be used as a custom

https://i.stack.imgur.com/mtlRi.png Could anyone assist me with storing a custom object that includes attributes from the StationRating interface? ...

What could be the reason behind TypeScript ignoring a variable's data type?

After declaring a typed variable to hold data fetched from a service, I encountered an issue where the returned data did not match the specified type of the variable. Surprisingly, the variable still accepted the mismatched data. My code snippet is as fol ...

Step-by-step guide on implementing a draggable component for selecting the year using React

I am looking to develop a draggable component in React without relying on any third-party library. Below, I have provided an image depicting how the component might look. Currently, my component code appears as follows: import React from 'react'; ...

The unit test is running successfully on the local environment, but it is failing on Jenkins with the error code TS2339, stating that the property 'toBeTruthy' is not recognized on the type 'Assertion'

I've been tackling a project in Angular and recently encountered an issue. Running 'npm run test' locally shows that my tests are passing without any problems. it('should create', () => { expect(component).toBeTruthy();}); How ...

Tips for preventing the error message "The property 'map' is not present on type 'string | string[]'."

I received an error message stating Property 'map' does not exist on type 'string | string[]': const data = [ ['1', ['11']], ['2', ['21']], ['3', ['31']], ] data.map(top ...