Currently, I am in the process of converting a React application that was previously not using TypeScript to now incorporate TypeScript. I am facing an issue with the use of React Hook Form's setValue method.
The component I am working on serves as a reusable container for data grid filters passed in as children. The values of the React Hook Form fields are read and written dynamically to and from a cache, causing the component to be unaware of the type of the field values object.
In the non-TypeScript version, I had no issues with this setup, as I could pass dynamic field names and values to setValue using the non-generic implementation of useForm.
However, with TypeScript, the definition of setValue looks like this:
(property) setValue: <never>(name: never, value: never, options?: Partial<{
shouldValidate: boolean;
shouldDirty: boolean;
shouldTouch: boolean;
}> | undefined) => void
The never type generic restricts me from providing a dynamic value (of type string) as the field name as shown below:
fields.forEach((field, i) => formMethods.setValue(field[0], field[1], { shouldDirty: true }));
As a result, I am encountering the error: Argument of type 'string' is not assignable to parameter of type 'never'
I am aware that in normal circumstances, I would define a type for the field values object and pass it as a generic to useForm. However, I am unsure how to handle dynamic types instead. Any suggestions?