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

Display the initial x list items without utilizing ngFor in Angular 2

In the template, there are 9 <li> elements, each with a *ngIf condition present. It is possible that 5 or more of them may return true, but the requirement is to only display the first 4 or less if needed. Priority is given to the order of the < ...

Apologies, but it seems there was an issue with the installation of the "@angular/compiler-cli" package

Despite thoroughly searching through various threads, I am still unable to find a solution to my problem. I have cloned the angular2 quickstart project and ensured that all module versions are up to date. For reference, here is the link to the repository ...

When transitioning to generics, the narrowing of types in TypeScript is sometimes lost

I am intrigued by this scenario where Test1 fails while Test2 succeeds. I wonder if there is a way to have Test1 pass without altering the generic signature: enum TableType { Shipment = "Shipment", Batch = "Batch", } type Test& ...

The specified function 'isFakeTouchstartFromScreenReader' could not be located within the '@angular/cdk/a11y' library

I encountered the following errors unexpectedly while working on my Angular 11 project: Error: ./node_modules/@angular/material/fesm2015/core.js 1091:45-77 "export 'isFakeTouchstartFromScreenReader' was not found in '@angular/cdk/a11y&a ...

I am interested in transforming an Angular 2 observable into a custom class

Having recently delved into the world of angular2, I've spent countless hours trying to tackle a particular challenge without success. My goal is to convert an observable from an HTTP call and store it in a class. Below are the key components involve ...

Next.js 13 app directory experiences 404 Not Found error due to dynamic routing issues

I recently built a straightforward to-do app using Next.js 13 paired with TypeScript. The process involved creating an array of objects, each comprising an id string and a name string. Subsequently, I iterated through the list and showcased the names withi ...

Issue with PassportJS and Express 4 failing to properly store cookies/session data

I have a situation with my Express 4 app using Passport 0.3.2. I've set up a passport-local strategy, and it's successfully retrieving the user information when the /session endpoint is provided with a username and password. The issue arises whe ...

What is the most efficient way to perform an inline property check and return a boolean value

Can someone help me with optimizing my TypeScript code for a function I have? function test(obj?: { someProperty: string}) { return obj && obj.someProperty; } Although WebStorm indicates that the return value should be a boolean, the TypeScript compil ...

Suggestions for efficiently filtering nested objects with multiple levels in RXJS within an Angular environment?

Just a Quick Query: Excuse me, I am new to Typescipt & RxJS. I have this JSON data: [ { "ID": "", "UEN": "", "Name": "", "Address": "", "Telephone&quo ...

How can we define a function using a generic type in this scenario using Typescript?

Here's a challenge that I'm facing. I have this specific type definition: type FuncType<T> = (value: T) => T I want to create a function using this type that follows this structure: const myFunc: FuncType<T> = (value) => valu ...

Incorporating XMLHttpRequest in my React Typescript App to trigger a Mailchimp API call, allowing users to easily sign up for the newsletter

My website needs to integrate Mailchimp's API in order for users to subscribe to a newsletter by entering their email into a field. I am looking to implement this without relying on any external libraries. To test out the functionality, I have set up ...

webpack is having trouble locating the src file, even though it should not be searching for it in the first place

I'm currently delving into the world of using TypeScript with React and am following a helpful tutorial at: https://blog.logrocket.com/how-why-a-guide-to-using-typescript-with-react-fffb76c61614 However, when attempting to run the webpack command thr ...

When using AngularJS 2, the class identity is lost when resolving a Promise during fetching

SUMMARY: I'm encountering an issue where I am fetching Object instances instead of Org instances from my data in Angular 2. Is there a way to retrieve Org objects directly or is this the expected behavior? DETAILS: In my Angular 2 project, I have mod ...

Typedi's constructor injection does not produce any defined output

I am utilizing typedi in a Node (express) project and I have encountered an issue related to injection within my service class. It seems that property injection works fine, but constructor injection does not. Here is an example where property injection wo ...

Guide for adjusting icon dimensions in Material-UI breakpoints

import { Container } from "@mui/material"; import * as React from "react"; import { Home } from "@mui/icons-material"; import PersonIcon from "@mui/icons-material/Person"; import FormatListBulletedIcon from "@mu ...

What is the best way to effectively personalize my Bootstrap variables using SASS?

After creating a web page and adding Bootstrap styling, I attempted to customize the Bootstrap variables, but encountered an issue where it did not seem to work despite no errors being displayed. I followed a tutorial on YouTube meticulously, but to no av ...

Establishing the initial state in React

Can someone help me with setting the default state in React? I'm working on a project that allows files to be dropped onto a div using TypeScript and React. I want to store these files in the state but I'm struggling with initializing the default ...

I am having trouble with a property that I believe should be recognized but is not

Here is the vocabulary I am working with: type MyHeaders = { Authorization: string; Accept: "application/json"; }; type MyGetOptions = { url: string; json: true; }; type MyOptionsWithHeaders = { headers: MyHeaders; }; type MyPostOptions ...

Using TypeScript to narrow down types within mapped types

Can you create a mapped type based on the property type? For example, if I want to map all properties with type String to Foo and all other types to Bar. Can this be done like this: type MappedType<T> = { [P in keyof T]: T[P] === String ? Foo : B ...

Problem with Invoking method of parent component from child component in Angular 4

Despite having all my event emitters set up correctly, there's one that seems to be causing issues. child.ts: @Component({ ... outputs: ['fileUploaded'] }) export class childComponent implements OnInit { ... fileUploaded ...