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!
The error "Argument of type string | undefined is not assignable to parameter of type string" occurs when a possibly undefined value is passed to a function that expects a string . To solve the error, use a type guard to verify the value is a string before passing it to the function.
The "Type 'string' is not assignable to type" TypeScript error occurs when we try to assign a value of type string to something that expects a different type, e.g. a more specific string literal type or an enum. To solve the error use a const or a type assertion.
The type any[] is an array type and may have any number of elements, so typescript will not allow it to be assigned here. The only values assignable to that prop are an empty array [] , or undefined . If you try to to assign an array type to that prop typescript will yell at you because that array might not be empty.
The error "Argument of type is not assignable to parameter of type 'never'" occurs when we declare an empty array without explicitly typing it and attempt to add elements to it. To solve the error, explicitly type the empty array, e.g. const arr: string[] = []; .
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.
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)} />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With