The parameter cannot be assigned a value of type 'string' as it requires a value that matches the format '`${string}` | `${string}.${string}` | `${string}.${number}`'

I recently updated my react-hook-forms from version 6 to version 7.

Following the instructions in the migration guide, I made changes to the register method. However, after making these changes, I encountered the following error:

The argument being passed is a string and not compatible with the parameter type '${string} | ${string}.${string} | ${string}.${number}'. TS2345

Even though I am passing a string name to the Register function correctly, it does not accept my parameter if it is not an exact string match.

If anyone has faced a similar issue or has any suggestions, I would greatly appreciate your help. Thank you in advance!

Answer №1

register() function in react-hook-form version 7 doesn't accept a regular string as input, but rather a string literal. The literal value should match one of the field names defined in the form:

interface IFormValues {
  firstName: string;
  lastName: string;
}
const { register, handleSubmit } = useForm<IFormValues>();

When providing a generic type to the useForm hook, the register method expects to receive either the literal firstName or lastName; passing any other string or value will result in a type error.

Solution

As described in the official example, when using useFieldArray and dynamically creating fields using map, it's necessary to explicitly assert the name as a constant before passing it to register. This is done to prevent type widening issues that can occur when mixing string literals with index numbers:

<input key={field.id} {...register(`test.${index}.test` as const)}  />

Answer №2

When utilizing the Controller feature, it is possible to include conditional rendering for the name property, which can make errors disappear magically. :)

const formFields = [
  {
    id: 1,
    name: "youtubeUrl",
    placeholder: "Youtube URL",
  },
  {
    id: 2,
    name: "videoName",
    placeholder: "Video Name",
  },
];

// Form section begins here
<form onSubmit={handleSubmit(onSubmit)}>
 {formFields.map((item) => {
  return (
    <Box key={item.id}>
      <Controller
       name={
       item.name === "youtubeUrl" ? "youtubeUrl" 
       : "videoName" } // <---- applying conditional rendering here
       control={control}
       render={({ field: { onChange, value } }) => (
       <TextField
       size="small"
       error={errors[item.name] ? true : false}
       fullWidth
       onChange={onChange}
       value={value}
       placeholder={item.placeholder}
       inputProps={{
       "aria-label": item.placeholder,
       }}
       />
       )}
       />
                    
   </Box>
 </form>

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

What are the steps to execute a Next.js app post cloning the repository?

After creating a Next.js app using npx create-next-app@latest, I proceeded to push the new application to a GitHub repository. Upon cloning the repository into a fresh directory, I encountered an issue while attempting to execute the app with npm run dev. ...

Set the parameter as optional when the type is null or undefined

I need to create a function that can take a route and an optional set of parameters, replacing placeholders in the route with the given params. The parameters should match the placeholders in the route, and if there are no placeholders, the params should b ...

Focusing on an input element in Angular2+

How do I set focus on an input element? Not with AngularDart, but similar to the approach shown in this question: <input type="text" [(ngModel)]="title" [focus] /> //or <input type="text" [(ngModel)]="title" autofocus /> Does Angular2 provi ...

When typing declarations are used, they clarify whether the entity being referenced is an Object or

I am currently working on aligning the Dockerode run typings to match the actual implementation. The issue arises when I invoke run as TypeScript consistently identifies the return value as a Promise. It seems that TypeScript is having trouble distinguish ...

Angular ReactiveForms not receiving real-time updates on dynamic values

I'm using reactive forms in Angular and I have a FormArray that retrieves all the values except for product_total. <tbody formArrayName="products"> <tr *ngFor="let phone of productForms.controls; let i=index" [formGroupName]="i"> ...

Encountering an error when attempting to generate a production build after running the npm install command with the

After adding the brotli-webpack-plugin as a devDependency, I encountered an issue when attempting to generate a production build using npm run build (which internally runs next build). The error message displayed was: Error: Cannot find module 'bro ...

Issue: The UserComponent is attempting to set the property 'id' of an undefined object, resulting in an error

An error has occurred indicating that the property 'id' cannot be set as it is undefined in the UserComponent file of user.component.ts. Here is the TypeScript code: import { Component, OnInit } from "@angular/core"; import { ActivatedRoute, Rou ...

What is the reason for the immediate application of the set function in a useState hook within asynchronous functions?

While working with multiple set functions of a useState hook, I noticed different behaviors when calling them in sync and async functions. function Test() { console.log('app rendering starts.'); const [a, setA] = useState(1); const [b ...

Learn how to update a fixed value by adding the content entered into the Input textfield using Material-UI

I made a field using the Input component from material-ui: <Input placeholder="0.00" value={rate} onChange={event => { this.setState({ `obj.rate`, event.target.value }); }} /> Whenever I input a rate into this field, ...

Cross-origin resource sharing (CORS) issue encountered while trying to play an mp

I am facing an issue with my React application where it is unable to play audio from a different source due to a CORS error. Example: Interestingly, when I visit https://www.w3schools.com/tags/tag_audio.asp, input the above URL and click play, it works fi ...

Error in IONIC 3: The code is unable to read the 'nativeElement' property due to an undefined value, resulting in a TypeError

I am currently learning about IONIC 3 and working on an app that utilizes the Google Maps API. However, when I try to launch my app, I encounter the following error message: inicio.html Error: Uncaught (in promise): TypeError: Cannot read property ' ...

What strategies and techniques should be considered when creating websites optimized for mobile devices?

With a wealth of experience in programming languages like Java, Python, and C, I actively engage in self-study to enhance my skills. While I have dabbled in creating mobile-friendly websites, upon reviewing my work, it is evident that my frontend developme ...

What is the reason behind the Typescript compiler not converting .ts files to .js files automatically?

Displayed below are the folders on the left showcasing my Typescript file in /src (blue) compiled into Javascript in /dist (purple) using tsc. https://i.stack.imgur.com/7XNkU.png In the source file on the left, there is a reference to a .ts module file t ...

How to dynamically disable a checkbox in Angular reactive forms depending on the value of another checkbox

I am attempting to deactivate the checkbox based on the value of other checkboxes. Only one of them can be activated at a time. When trying to activate one of the checkboxes, I encounter an issue where the subscribed value is being repeated multiple times ...

The error "Rollup EMFILE: exceeding file limit with material-ui icons" is appearing due to an

I have implemented a design system based on Material-ui version 5, with rollup as my bundler. Within one of the custom components, I am importing an icon from Mui5 import { Search } from "@material-ui/icons" During the rollup build process, I e ...

Enhancing Security: Implementing Node.js API Authentication

Looking for guidance on setting up multiple authentications with different roles in Next.js development. Can anyone help me navigate this aspect of website building? Using Next.js for the frontend Utilizing Node.js and JWT (JSON web token) for the backend ...

How can I bind the ID property of a child component from a parent component in Angular 2 using @Input?

I have a unique requirement in my parent component where I need to generate a child component with a distinct ID, and then pass this ID into the child component. The purpose of passing the unique ID is for the child component to use it within its template. ...

tips for concealing a row in the mui data grid

I am working on a data grid using MUI and I have a specific requirement to hide certain rows based on a condition in one of the columns. The issue is that while there are props available for hiding columns, such as hide there doesn't seem to be an eq ...

Retrieve the values of private variables within a defined function

While experimenting with typescript, I have encountered an issue that I can't seem to resolve. My project involves using Angular, so I will present my problem within that context. Here is a snippet of my code: class PersonCtrl{ private $scope: I ...

The getServerSession() method in NextAuth fails to retrieve all of the user fields when called in an API route

I am currently working on implementing an API route where I need to verify the user's authentication status and check if they are an admin. As part of this process, I attempted to utilize the getServerSession method, however, it returned a session wit ...