How to correctly type a component prop for a form instance from a custom createFormHook? #1707
Unanswered
heinsenberg82
asked this question in
Q&A
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hello. I'm seeking guidance on the idiomatic way to type a component prop that accepts a form instance created by a custom hook (
createFormHook
). The core challenge is that the form's data type is dynamic based on the options passed to the hook at runtime.The Setup
First, I have a central
form.ts
file to create a custom hook with pre-configured components, as recommended in the docs:form.ts
In a parent component, I use this hook to create a form instance with specific
defaultValues
:ParentComponent.tsx
The Problem
In
ChildComponent.tsx
, I need to define the type for theform
prop. All my attempts have led to TypeScript errors.ChildComponent.tsx
What I've Tried
Using
FormApi<T>
directly:form: FormApi<typeof options.defaultValues>
(TS2707) Generic type 'FormApi<...>' requires between 11 and 12 type arguments.
This is understandable, as the custom hook returns a much more specific type.Using
ReturnType
on the custom hook:type AppForm = ReturnType<typeof useAppForm>;
unknown
(e.g.,AppFieldExtendedReactFormApi<unknown, ...>
). When I pass the specific form instance from the parent, I get an assignment error:(TS2322) Type 'AppFormInstance<{nrProcesso: string}>' is not assignable to 'AppFormInstance<unknown>'
.Creating a Generic Child Component:
ChildComponent
generic and trying various ways to type the prop, such asform: FormApi<TFormData>
or creating a genericAppFormInstance<TFormData>
type utility.TS2707
error (becauseFormApi<T>
is not the same as the custom hook's return type) or complex assignment errors (TS2322
) because my manually constructed generic types don't match the "branded" type returned bycreateFormHook
.My Question
What is the correct and idiomatic way to type the
form
prop inChildComponent
so that it can accept any instance created byuseAppForm
, while maintaining full type safety and inference for the specific data shape (defaultValues
) inside the component?Thank you for your time and any guidance you can provide.
Beta Was this translation helpful? Give feedback.
All reactions