W
W
wonderingpeanut2022-03-31 14:29:02
typescript
wonderingpeanut, 2022-03-31 14:29:02

How to create a type from an existing type that will only have some fields of the existing type?

Greetings.
There is the following code:

type FormProps<T extends FieldValues> = {
  defaultValues?: DefaultValues<T>;
  onSubmit: (data: UnpackNestedValue<T>) => void;
  children: ({ register, formState }: UseFormReturn<T>) => ReactNode;
};
export const Form = <T,>({ defaultValues, onSubmit, children }: FormProps<T>) => {
  const { handleSubmit, reset, setValue, control, register } = useForm({ defaultValues });

  return <form onSubmit={handleSubmit(onSubmit)}>{children({ register, formState })}</form>;
};

At the moment, if you pass only register and formState to children, the typescript swears that I did not specify all the required properties (an object is required, which is returned by the useForm hook).

How do I write the type of the children property so that it only needs some of the properties of the UseFormReturn object?
It was exactly what was required. Partial> doesn't fit.

Obviously, you can explicitly specify the type of each required property:

...
children: ({ register, formState }: { register: UseFormRegister<T>, formState: FormState<T> }) => ReactNode;
...


But is it possible to somehow get the type from the existing UseFormReturn type?
Playground

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
WbICHA, 2022-03-31
@wonderingpeanut

Pick

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question