React Hook form makes my fields optional and how to handle it?

i am new to react-hook-form. i have my form schema like this.

My name property is required. but when i use spread syntax to create data as payload to send to server, TS always says that the property is optional. Many properties are required but get warned.

How should i handle this problem? Could you give me the correct way to handle this please?

const formSchema = z.object({
    name: z.string().min(1, {
      message: t("common.error.min_char", { name: t("common.name"), min: 1 }),
    }),
    placeDescription: z.string().optional(),
    categoryId: z.string().optional(),
...
});

const formData = {...form.getValues()};

const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      categoryId: "",
      subCategoryId: "",
      name: "",
    }
});

const _data: ITourProductSyncData = {
   ...formData,
   // other properties
}

right now, i have to map all the properties once again. Is there a better way to handle this?

TypeScript sees your properties as optional because form.getValues() returns all fields but with optional types, not guaranteed required values.

To fix this without remapping all properties manually, you should:

  1. Use form.getValues() only after form validation to ensure required fields are present.
  2. Or better, get validated data from form.handleSubmit or form.getValues() with proper type assertion.

Recommended approach:

const onSubmit = (data: z.infer<typeof formSchema>) => {
  // data here has correct required properties
  const _data: ITourProductSyncData = {
    ...data,
    // other properties
  };
  // send _data to server
};

<form onSubmit={form.handleSubmit(onSubmit)}>
  {/* form fields */}
</form>

This way, data passed to onSubmit is guaranteed to match your schema, so TS knows required fields exist.


If you need to get form values outside submit handler, assert like this:

const formData = form.getValues() as z.infer<typeof formSchema>;

but be careful — this skips runtime validation.


Summary:

  • Use handleSubmit callback parameter for fully validated & typed data.
  • Avoid spreading form.getValues() directly before validation.
  • If needed, use type assertion on form.getValues().
  • No need to remap each property manually when you use the validated data from handleSubmit.