Skip to content

Nested Form Sections with Typesafe Typescript #9345

Answered by chamatt
chamatt asked this question in Q&A
Discussion options

You must be logged in to vote

I was able to achieve a good level of typesafety on this, and I'm using this from now on until we have a better alternative.
The main magic is the following utility function:

export const narrowForm = <TFieldValues extends FieldValues = FieldValues, TContext = any>(
 form: any,
) => form as unknown as UseFormReturn<TFieldValues, TContext>

And you'd define the section as:

// Define the fields that the section will contain
type ExampleFormValues = {
  name: string
  age: number
}

const ExampleSection = <T extends FieldValues>({
  form,
}: {
  form: UseFormReturn<T & ExampleFormValues>
}) => {
  const { register } = narrowForm<ExampleFormValues>(form)
  return (
    <div>
      <input {...r…

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by chamatt
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants