react-hook-form icon indicating copy to clipboard operation
react-hook-form copied to clipboard

issue: error of union type does not exist in type

Open Istanful opened this issue 6 months ago • 1 comments

Version Number

7.58.1

Codesandbox/Expo snack

https://codesandbox.io/p/sandbox/4g7z9p

Steps to reproduce

  1. Use the zod resolver with useForm
  2. Declare a schema with a union type where one of the unions does not have the same keys.
  3. Try to access the error of a key that only exists on one of the unions

Expected behaviour

The error should exist on the type. Instead it can't be indexed.

In my attached example I added an example solution. The example solution uses a custom KeysOfUnion type to extract all keys in the union regardless of the shape. I believe this is an ok solution even though the types technically is not correct for some unions. I believe it's ok due to that it can always return undefined anyways.

What browsers are you seeing the problem on?

No response

Relevant log output


Code of Conduct

  • [x] I agree to follow this project's Code of Conduct

Example fix

type KeysOfUnion<T> = T extends T ? keyof T : never;

type FieldErrorsImpl<T extends FieldValues = FieldValues> = {
  [K in KeysOfUnion<T>]?: T[K] extends BrowserNativeObject | Blob
    ? FieldError
    : K extends "root" | `root.${string}`
      ? GlobalError
      : T[K] extends object
        ? Merge<FieldError, FieldErrorsImpl<T[K]>>
        : FieldError;
};

type FieldErrors<T extends FieldValues = FieldValues> = Partial<
  FieldValues extends IsAny<FieldValues>
    ? any
    : FieldErrorsImpl<DeepRequired<T>>
> & {
  root?: Record<string, GlobalError> & GlobalError;
};

Istanful avatar Jul 02 '25 09:07 Istanful

Might be related to same issue? https://github.com/react-hook-form/react-hook-form/issues/12924

seemX17 avatar Jul 03 '25 12:07 seemX17