I am trying to build FormBuilder
component. And have a code like this:
type FormValues = {
[i: number]: {
[j: number]: string;
};
};
export type FormBuilderProps<> = {
schema: Array<{
legend: string;
fields: Array<TF | SF>;
}>;
onSubmit: SubmitHandler<FormValues>;
};
export function FormBuilder(props: FormBuilderProps) {
const { schema, onSubmit } = props;
const { handleSubmit, control } = useForm({
resolver: useMemo(() => {
return zodResolver(
z.object(
schema.reduce((result, { fields }, i) => {
return Object.assign({}, result, {
[i]: fields.reduce((rules, { schema }, j) => {
if (schema) {
return Object.assign({}, rules, {
[j]: schema,
});
}
return rules;
}, {}),
});
}, {}),
),
);
}, [schema]),
});
return (
<form
onSubmit={handleSubmit((data) => {
return onSubmit(data);
})}
>
{schema.map((fieldset, i) => {
const { fields } = fieldset;
return (
<fieldset key={`fieldset-${i}`}>
{fields.map((field, j) => {
const name = `${i}.${j}`;
return (
<Controller
control={control}
key={`field-${j}`}
name={name}
render={(renderProps) => {
if (field.kind === "text") {
const { props } = field;
return <input {...renderProps.field} {...props} />;
}
if (field.kind === "select") {
const { props } = field;
return <input {...renderProps.field} {...props} />;
}
throw new Error(`Unsupported kind of field`);
}}
/>
);
})}
</fieldset>
);
})}
<input type='submit' />
</form>
);
}
The type of the name
property should be Path<FieldValues>
, but I don't understand at all how to describe this type so that it matches the type of the schema
field. So I get the error
Type 'string' is not assignable to type 'Path<TFieldValues>'
controller.d.ts(20, 5): The expected type comes from property 'name' which is declared here on type 'IntrinsicAttributes & { render: ({ field, fieldState, formState, }: { field: ControllerRenderProps<TFieldValues, Path<TFieldValues>>; fieldState: ControllerFieldState; formState: UseFormStateReturn<...>; }) => ReactElement<...>; } & UseControllerProps<...>'
Right now my FormValues
type is very abstract and I think that's why I get this error.
How should I describe the FormValues type so I don't get this error?
Playground