Argument of type 'string' is not assignable to parameter of type '`${string}` | `${string}.${string}` | `${string}.${number}`'

Viewed 17444

I've migrated react-hook-forms from v.6 to v.7.

After changing the register method, as pointed out in the migration guide, the following error occurs:

Argument of type 'string' is not assignable to parameter of type '${string} | ${string}.${string} | ${string}.${number}'. TS2345

Register expects a string name, which I provide correctly with a param which for sure is a string, but anyhow it doesn't accept my parameter if I don't pass exactly string.

Anyone with a similar issue or any idea is highly appreciated. Thanks in advance!

1 Answers

register() in react-hook-form v7 does not accept a string but string literal. The literal value is one of the field name in the form:

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

When you assign a generic type parameter to the useForm hook, the register expects to receive either firstName or lastName literal, a string or anything else will throw a type error.

Solution

According to the official example, if you are using useFieldArray and the fields are created dynamically using map, you need to assert the name as a const before passing to the register, this is because of type widening when you mix string literal with the index number:

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