React Hook Form Built-in Solution for Generating Typed Paths in Array Fields?

137 Views Asked by At

I'm currently working with React Hook Form and facing a challenge in generating typed paths for fields within an array in my form data. My specific use case involves constructing path strings in the format fieldName.$index.fieldProperty.

For context, here's an example data type I'm working with:

type BookDTO = {
    authors: Array<{
        id: string;
        name: string;
        //....
    }>;
    //....
};

To address this, I've developed a custom TypeScript utility type that constructs these path strings, but this just takes into account the first element of an array:

type FieldArrayFromValue<TFieldName extends FieldValues, RFieldName extends FieldArrayPath<TFieldName>> = {
    [P in RFieldName]: [FieldArray<TFieldName, RFieldName>];
};

// Usage example
type AuthorFieldPaths = FieldPath<FieldArrayFromValue<BookDTO, 'authors'>>;

With this utility type, I can generate paths such as authors.$0.name, authors.$1.id, etc. This solution almost functions well, but I'm curious if React Hook Form offers a more built-in or streamlined method to achieve the same result. Right now authors.$1.name gives an error for example.

Given that handling arrays of fields is a frequent requirement in form handling, I'm wondering if there's an existing feature or utility in React Hook Form that simplifies this process. Does anyone know of a built-in approach in React Hook Form for generating these types of typed paths?

Thanks in advance. Have a good one!

0

There are 0 best solutions below