ronantakizawa/codereview-bench huggingface dataset:
Repository: react-hook-form/react-hook-form
File: src/useWatch.ts (TypeScript)

Code before:
 *
 * @remarks
 *
 * [API](https://react-hook-form.com/api/usewatch) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-usewatch-h9i5e)
 *
 * @param props - defaultValue, disable subscription and match exact name.
 *
 * @example
 * ```tsx
 * const { watch } = useForm();
 * const values = useWatch({
 *   control,
 *   defaultValue: {
 *     name: "data"
 *   },
 *   exact: false,
 * })
 * ```
 */
export function useWatch<TFieldValues extends FieldValues>(props: {
  defaultValue?: DeepPartialSkipArrayKey<TFieldValues>;
  control?: Control<TFieldValues>;
  disabled?: boolean;
  exact?: boolean;
}): DeepPartialSkipArrayKey<TFieldValues>;
/**
 * Custom hook to subscribe to field change and isolate re-rendering at the component level.
 *
 * @remarks
 *
 * [API](https://react-hook-form.com/api/usewatch) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-usewatch-h9i5e)
 *
 * @param props - defaultValue, disable subscription and match exact name.
 *
 * @example
 * ```tsx
 * const { watch } = useForm();
 * const values = useWatch({
 *   control,
 *   name: "fieldA",
 *   defaultValue: "default value",
 *   exact: false,
 * })
 * ```
 */
export function useWatch<
  TFieldValues extends FieldValues,
  TFieldName extends PathString,
>(props: {
  name: Auto.FieldPath<TFieldValues, TFieldName>;
  defaultValue?: FieldPathValue<TFieldValues, TFieldName>;

Review comment (suggestion):
`name: readonly [...TFieldNames];`

@felixschorer shouldn't this above to be the correct one to fix the generic 

Code after:
 *
 * @remarks
 *
 * [API](https://react-hook-form.com/api/usewatch) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-usewatch-h9i5e)
 *
 * @param props - defaultValue, disable subscription and match exact name.
 *
 * @example
 * ```tsx
 * const { watch } = useForm();
 * const values = useWatch({
 *   control,
 *   name: ["fieldA", "fieldB"],
 *   defaultValue: {
 *     fieldA: "data",
 *     fieldB: "data"
 *   },
 *   exact: false,
 * })
 * ```
 */
export function useWatch<
  TFieldValues extends FieldValues,
  TFieldNames extends readonly PathString[],
>(props: {
  name: readonly [...Auto.FieldPaths<TFieldValues, TFieldNames>];
  defaultValue?: FieldPathValues<TFieldValues, TFieldNames>;
  control?: Control<TFieldValues>;
  disabled?: boolean;
  exact?: boolean;
}): FieldPathValues<TFieldValues, TFieldNames>;
/**
 * Subscribe to the entire form values change and re-render at the hook level.
 *
 * @remarks
 *
 * [API](https://react-hook-form.com/api/usewatch) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-usewatch-h9i5e)
 *
 * @param props - defaultV
 alue, disable subscription and match exact name.
 *
 * @example
 * ```tsx
 * const { watch } = useForm();
 * const values = useWatch({
 *   control,
 *   defaultValue: {
 *     name: "data"
 *   },
 *   exact: false,
 * })
Repository: react-hook-form/react-hook-form
File: src/types/utils.ts (TypeScript)

Code before:
export type BrowserNativeObject = Date | FileList | File;

export type EmptyObject = { [K in string | number]: never };

export type NonUndefined<T> = T extends undefined ? never : T;

export type LiteralUnion<T extends U, U extends Primitive> =
  | T
  | (U & { _?: never });

export type DeepPartial<T> = T extends BrowserNativeObject | NestedValue
  ? T
  : { [K in keyof T]?: DeepPartial<T[K]> };

export type DeepPartialSkipArrayKey<T> = T extends
  | BrowserNativeObject
  | NestedValue
  ? T
  : T extends ReadonlyArray<any>
  ? { [K in keyof T]: DeepPartialSkipArrayKey<T[K]> }
  : { [K in keyof T]?: DeepPartialSkipArrayKey<T[K]> };

export type UnPackDefaultValues<TFieldValues> =
  TFieldValues extends () => Promise<any>
    ? Awaited<ReturnType<TFieldValues>>
    : TFieldValues;

/**
 * Checks whether the type is any
 * See {@link https://stackoverflow.com/a/49928360/3406963}
 * @typeParam T - type which may be any
 * ```
 * IsAny<any> = true
 * IsAny<string> = false
 * ```
 */
export type IsAny<T> = 0 extends 1 & T ? true : false;

/**
 * Checks whether the type is never
 * @typeParam T - type which may be never
 * ```
 * IsAny<never> = true
 * IsAny<string> = false
 * ```
 */
export type IsNever<T> = [T] extends [never] ? true : false;

export type DeepMap<T, TValue> = IsAny<T> extends true
  ? any
  : T extends BrowserNativeObject | NestedValue

Review comment (suggestion):
I think this can be shortened.
```suggestion
  TFieldValues extends () => Promise<infer U> ? U : TFieldValues;
```

Code after:
export type BrowserNativeObject = Date | FileList | File;

export type EmptyObject = { [K in string | number]: never };

export type NonUndefined<T> = T extends undefined ? never : T;

export type LiteralUnion<T extends U, U extends Primitive> =
  | T
  | (U & { _?: never });

export type DeepPartial<T> = T extends BrowserNativeObject | NestedValue
  ? T
  : { [K in keyof T]?: DeepPartial<T[K]> };

export type DeepPartialSkipArrayKey<T> = T extends
  | BrowserNativeObject
  | NestedValue
  ? T
  : T extends ReadonlyArray<any>
  ? { [K in keyof T]: DeepPartialSkipArrayKey<T[K]> }
  : { [K in keyof T]?: DeepPartialSkipArrayKey<T[K]> };

export type UnPackDefaultValues<TFieldValues> =
  TFieldValues extends () => Promise<infer U> ? U : TFieldValues;

/**
 * Checks whether the type is any
 * See {@link https://stackoverflow.com/a/49928360/3406963}
 * @typeParam T - type which may be any
 * ```
 * IsAny<any> = true
 * IsAny<string> = false
 * ```
 */
export type IsAny<T> = 0 extends 1 & T ? true : false;

/**
 * Checks whether the type is never
 * @typeParam T - type which may be never
 * ```
 * IsAny<never> = true
 * IsAny<string> = false
 * ```
 */
export type IsNever<T> = [T] extends [never] ? true : false;

export type DeepMap<T, TValue> = IsAny<T> extends true
  ? any
  : T extends BrowserNativeObject | NestedValue
  ? TValue
  : T extends object
Repository: react-hook-form/react-hook-form
File: src/types/form.ts (TypeScript)

Code before:
  boolean
>;

export type FormStateProxy<TFieldValues extends FieldValues = FieldValues> = {
  isDirty: boolean;
  isValidating: boolean;
  dirtyFields: FieldNamesMarkedBoolean<TFieldValues>;
  touchedFields: FieldNamesMarkedBoolean<TFieldValues>;
  errors: boolean;
  isValid: boolean;
};

export type ReadFormState = { [K in keyof FormStateProxy]: boolean | 'all' };

export type FormState<TFieldValues extends FieldValues> = {
  isDirty: boolean;
  isSubmitted: boolean;
  isSubmitSuccessful: boolean;
  isSubmitting: boolean;
  isValidating: boolean;
  isValid: boolean;
  submitCount: number;
  defaultValues?:
    | (TFieldValues extends () => Promise<any>
        ? Awaited<ReturnType<TFieldValues>>
        : TFieldValues)
    | undefined
    | Readonly<DeepPartial<TFieldValues>>;
  dirtyFields: Partial<Readonly<FieldNamesMarkedBoolean<TFieldValues>>>;
  touchedFields: Partial<Readonly<FieldNamesMarkedBoolean<TFieldValues>>>;
  errors: FieldErrors<TFieldValues>;
};

export type KeepStateOptions = Partial<{
  keepDirtyValues: boolean;
  keepErrors: boolean;
  keepDirty: boolean;
  keepValues: boolean;
  keepDefaultValues: boolean;
  keepIsSubmitted: boolean;
  keepTouched: boolean;
  keepIsValid: boolean;
  keepSubmitCount: boolean;
}>;

export type SetFieldValue<TFieldValues extends FieldValues> =
  FieldValue<TFieldValues>;

export type RefCallBack = (instance: any) => void;

export type UseFormRegisterReturn<

Review comment (suggestion):
```suggestion
    | UnPackDefaultValues<TFieldValues>
```

Code after:
export type FieldNamesMarkedBoolean<TFieldValues extends FieldValues> = DeepMap<
  DeepPartial<TFieldValues>,
  boolean
>;

export type FormStateProxy<TFieldValues extends FieldValues = FieldValues> = {
  isDirty: boolean;
  isValidating: boolean;
  dirtyFields: FieldNamesMarkedBoolean<TFieldValues>;
  touchedFields: FieldNamesMarkedBoolean<TFieldValues>;
  errors: boolean;
  isValid: boolean;
};

export type ReadFormState = { [K in keyof FormStateProxy]: boolean | 'all' };

export type FormState<TFieldValues extends FieldValues> = {
  isDirty: boolean;
  isSubmitted: boolean;
  isSubmitSuccessful: boolean;
  isSubmitting: boolean;
  isValidating: boolean;
  isValid: boolean;
  submitCount: number;
  defaultValues?:
    | UnPackDefaultValues<TFieldValues>
    | undefined
    | Readonly<DeepPartial<TFieldValues>>;
  dirtyFields: Partial<Readonly<FieldNamesMarkedBoolean<TFieldValues>>>;
  touchedFields: Partial<Readonly<FieldNamesMarkedBoolean<TFieldValues>>>;
  errors: FieldErrors<TFieldValues>;
};

export type KeepStateOptions = Partial<{
  keepDirtyValues: boolean;
  keepErrors: boolean;
  keepDirty: boolean;
  keepValues: boolean;
  keepDefaultValues: boolean;
  keepIsSubmitted: boolean;
  keepTouched: boolean;
  keepIsValid: boolean;
  keepSubmitCount: boolean;
}>;

export type SetFieldValue<TFieldValues extends FieldValues> =
  FieldValue<TFieldValues>;

export type RefCallBack = (instance: any) => void;

export type UseFormRegisterReturn<
Repository: react-hook-form/react-hook-form
File: src/useWatch.ts (TypeScript)

Code before:
          _name.current as InternalFieldName,
          formState.name,
          exact,
        )
      ) {
        const fieldValues = generateWatchOutput(
          _name.current as InternalFieldName | InternalFieldName[],
          control._names,
          formState.values || control._formValues,
        );

        updateValue(
          isUndefined(fieldValues) ? defaultValue : cloneObject(fieldValues),
        );
      }
    },
  });

  const [value, updateValue] = React.useState<unknown>(
    isUndefined(defaultValue)
      ? control._getWatch(name as InternalFieldName)
      : control._getWatch(
          name as InternalFieldName,
          defaultValue as DeepPartialSkipArrayKey<TFieldValues>,
        ),
  );

  React.useEffect(() => control._removeUnmounted());

  return value;
}


Review comment (refactor):
I think we can simplify to the following

```tsx
const [value, updateValue] = React.useState<unknown>(
  control._getWatch(
    name as InternalFieldName,
    defaultValue as DeepPartialSkipArrayKey<TFieldValues>,
  ),
);
```

Code after:
          _name.current as InternalFieldName,
          formState.name,
          exact,
        )
      ) {
        const fieldValues = generateWatchOutput(
          _name.current as InternalFieldName | InternalFieldName[],
          control._names,
          formState.values || control._formValues,
        );

        updateValue(
          isUndefined(fieldValues) ? defaultValue : cloneObject(fieldValues),
        );
      }
    },
  });

  const [value, updateValue] = React.useState<unknown>(
    control._getWatch(
      name as InternalFieldName,
      defaultValue as DeepPartialSkipArrayKey<TFieldValues>,
    ),
  );

  React.useEffect(() => control._removeUnmounted());

  return value;
}
Repository: react-hook-form/react-hook-form
File: src/types/errors.ts (TypeScript)

Code before:
};

export type FieldError = {
  type: LiteralUnion<keyof RegisterOptions, string>;
  root?: FieldError;
  ref?: Ref;
  types?: MultipleFieldErrors;
  message?: Message;
};

export type ErrorOption = {
  message?: Message;
  type?: LiteralUnion<keyof RegisterOptions, string>;
  types?: MultipleFieldErrors;
};

export type DeepRequired<T> = T extends BrowserNativeObject | Blob
  ? T
  : {
      [K in keyof T]-?: NonNullable<DeepRequired<T[K]>>;
    };

export type FieldErrorsImpl<T extends FieldValues = FieldValues> = {
  [K in keyof T]?: T[K] extends BrowserNativeObject | Blob
    ? FieldError
    : T[K] extends object
    ? Merge<FieldError, FieldErrorsImpl<T[K]>>
    : FieldError;
};

export type FieldErrors<T extends FieldValues = FieldValues> = Partial<
  FieldValues extends IsAny<FieldValues>
    ? any
    : FieldErrorsImpl<DeepRequired<T>>
>;

export type InternalFieldErrors = Partial<
  Record<InternalFieldName, FieldError>
>;


Review comment (bug):
Unfortunately, this breaks error types in cases where `formState.error` is erroneously assumed to be a `GlobalError` while it's just a nested object.

In my case, I use
`const { formState: { errors } } = useFormContext<MyCustomField>()`
where `MyCustomField` has properties which are again objects.

When reading out a specific error, it looks somehow like this:
`const specificError = errors.definition?.configuration?.recipients as FieldError | undefined` 

This was already difficult before this PR which force me to add the user-defined type cast at the end. But now, it will fail already when reading `definition` with this error:
```
Property 'configuration' does not exist on type 'Partial<{ type: string | number; message: string; }>'.ts(2339)
```

Code after:
};

export type FieldError = {
  type: LiteralUnion<keyof RegisterOptions, string>;
  root?: FieldError;
  ref?: Ref;
  types?: MultipleFieldErrors;
  message?: Message;
};

export type ErrorOption = {
  message?: Message;
  type?: LiteralUnion<keyof RegisterOptions, string>;
  types?: MultipleFieldErrors;
};

export type DeepRequired<T> = T extends BrowserNativeObject | Blob
  ? T
  : {
      [K in keyof T]-?: NonNullable<DeepRequired<T[K]>>;
    };

export type FieldErrorsImpl<T extends FieldValues = FieldValues> = {
  [K in keyof T]?: T[K] extends BrowserNativeObject | Blob
    ? FieldError
    : T[K] extends GlobalError
    ? GlobalError
    : T[K] extends object
    ? Merge<FieldError, FieldErrorsImpl<T[K]>>
    : FieldError;
};

export type GlobalError = Partial<{
  type: string | number;
  message: string;
}>;

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

export type InternalFieldErrors = Partial<
  Record<InternalFieldName, FieldError>
>;
Repository: react-hook-form/react-hook-form
File: src/logic/createFormControl.ts (TypeScript)

Code before:
        ? isEmptyObject((await _executeSchema()).errors)
        : await executeBuiltInValidation(_fields, true);

      if (isValid !== _formState.isValid) {
        _subjects.state.next({
          isValid,
        });
      }
    }
  };

  const _updateIsValidating = () => {
    const isAnyFieldValidating = Object.values(
      _formState.validatingFields,
    ).some((val) => val);
    _proxyFormState.isValidating &&
      _subjects.state.next({
        isValidating: isAnyFieldValidating,
      });
  };

  const _updateValidatingFields = (isValidating: boolean, name: string) => {
    set(_formState.validatingFields, name, isValidating);
    _subjects.state.next({
      validatingFields: _formState.validatingFields,
    });
    _updateIsValidating();
  };

  const _updateFieldArray: BatchFieldArrayUpdate = (
    name,
    values = [],
    method,
    args,
    shouldSetValues = true,
    shouldUpdateFieldsAndState = true,
  ) => {
    if (args && method) {
      _state.action = true;
      if (shouldUpdateFieldsAndState && Array.isArray(get(_fields, name))) {
        const fieldValues = method(get(_fields, name), args.argA, args.argB);
        shouldSetValues && set(_fields, name, fieldValues);
      }

      if (
        shouldUpdateFieldsAndState &&
        Array.isArray(get(_formState.errors, name))
      ) {
        const errors = method(
          get(_formState.errors, name),
          args.argA,

Review comment (suggestion):
can move to the `_updateIsValidating` function and wrapped within the proxy

Code after:
      const isValid = _options.resolver
        ? isEmptyObject((await _executeSchema()).errors)
        : await executeBuiltInValidation(_fields, true);

      if (isValid !== _formState.isValid) {
        _subjects.state.next({
          isValid,
        });
      }
    }
  };

  const _updateIsValidating = (isValidating: boolean, names: string[]) => {
    if (!(_proxyFormState.isValidating || _proxyFormState.validatingFields)) {
      return;
    }
    names.forEach((name) => {
      set(_formState.validatingFields, name, isValidating);
    });
    _formState.isValidating = objectHasTruthyValue(_formState.validatingFields);
    _subjects.state.next({
      validatingFields: _formState.validatingFields,
      isValidating: _formState.isValidating,
    });
  };

  const _updateFieldArray: BatchFieldArrayUpdate = (
    name,
    values = [],
    method,
    args,
    shouldSetValues = true,
    shouldUpdateFieldsAndState = true,
  ) => {
    if (args && method) {
      _state.action = true;
      if (shouldUpdateFieldsAndState && Array.isArray(get(_fields, name))) {
        const fieldValues = method(get(_fields, name), args.argA, args.argB);
        shouldSetValues && set(_fields, name, fieldValues);
      }

      if (
        shouldUpdateFieldsAndState &&
        Array.isArray(get(_formState.errors, name))
      ) {
        const errors = method(
          get(_formState.errors, name),
          args.argA,
          args.argB,
        );
        shouldSetValues && set(_formState.errors, name, errors);
Repository: react-hook-form/react-hook-form
File: src/logic/createFormControl.ts (TypeScript)

Code before:
  shouldFocusError: true,
} as const;

export function createFormControl<
  TFieldValues extends FieldValues = FieldValues,
  TContext = any,
>(
  props: UseFormProps<TFieldValues, TContext> = {},
  flushRootRender: () => void,
): Omit<UseFormReturn<TFieldValues, TContext>, 'formState'> {
  let _options = {
    ...defaultOptions,
    ...props,
  };
  let _formState: FormState<TFieldValues> = {
    submitCount: 0,
    isDirty: false,
    isLoading: isFunction(_options.defaultValues),
    isValidating: false,
    isSubmitted: false,
    isSubmitting: false,
    isSubmitSuccessful: false,
    isValid: false,
    touchedFields: {},
    dirtyFields: {},
    errors: isObject(_options.errors) ? _options.errors || {} : {},
    disabled: false,
  };
  let _fields: FieldRefs = {};
  let _defaultValues =
    isObject(_options.defaultValues) || isObject(_options.values)
      ? cloneObject(_options.defaultValues || _options.values) || {}
      : {};
  let _formValues = _options.shouldUnregister
    ? {}
    : cloneObject(_defaultValues);
  let _state = {
    action: false,
    mount: false,
    watch: false,
  };
  let _names: Names = {
    mount: new Set(),
    unMount: new Set(),
    array: new Set(),
    watch: new Set(),
  };
  let delayErrorCallback: DelayCallback | null;
  let timer = 0;
  const _proxyFormState = {
    isDirty: false,

Review comment (suggestion):
```suggestion
    errors: _options.errors || {},
```

Will do 👍 

Code after:
  shouldFocusError: true,
} as const;

export function createFormControl<
  TFieldValues extends FieldValues = FieldValues,
  TContext = any,
>(
  props: UseFormProps<TFieldValues, TContext> = {},
  flushRootRender: () => void,
): Omit<UseFormReturn<TFieldValues, TContext>, 'formState'> {
  let _options = {
    ...defaultOptions,
    ...props,
  };
  let _formState: FormState<TFieldValues> = {
    submitCount: 0,
    isDirty: false,
    isLoading: isFunction(_options.defaultValues),
    isValidating: false,
    isSubmitted: false,
    isSubmitting: false,
    isSubmitSuccessful: false,
    isValid: false,
    touchedFields: {},
    dirtyFields: {},
    errors: _options.errors || {},
    disabled: false,
  };
  let _fields: FieldRefs = {};
  let _defaultValues =
    isObject(_options.defaultValues) || isObject(_options.values)
      ? cloneObject(_options.defaultValues || _options.values) || {}
      : {};
  let _formValues = _options.shouldUnregister
    ? {}
    : cloneObject(_defaultValues);
  let _state = {
    action: false,
    mount: false,
    watch: false,
  };
  let _names: Names = {
    mount: new Set(),
    unMount: new Set(),
    array: new Set(),
    watch: new Set(),
  };
  let delayErrorCallback: DelayCallback | null;
  let timer = 0;
  const _proxyFormState = {
    isDirty: false,
Repository: react-hook-form/react-hook-form
File: src/useForm.ts (TypeScript)

Code before:
 * }
 * ```
 */
export function useForm<
  TFieldValues extends FieldValues = FieldValues,
  TContext = any,
  TTransformedValues extends FieldValues | undefined = undefined,
>(
  props: UseFormProps<TFieldValues, TContext> = {},
): UseFormReturn<TFieldValues, TContext, TTransformedValues> {
  const _formControl = React.useRef<
    UseFormReturn<TFieldValues, TContext, TTransformedValues> | undefined
  >();
  const _values = React.useRef<typeof props.values>();
  const [formState, updateFormState] = React.useState<FormState<TFieldValues>>({
    isDirty: false,
    isValidating: false,
    isLoading: isFunction(props.defaultValues),
    isSubmitted: false,
    isSubmitting: false,
    isSubmitSuccessful: false,
    isValid: false,
    submitCount: 0,
    dirtyFields: {},
    touchedFields: {},
    errors: isObject(props.errors) ? props.errors || {} : {},
    disabled: false,
    defaultValues: isFunction(props.defaultValues)
      ? undefined
      : props.defaultValues,
  });

  if (!_formControl.current) {
    _formControl.current = {
      ...createFormControl(props, () =>
        updateFormState((formState) => ({ ...formState })),
      ),
      formState,
    };
  }

  const control = _formControl.current.control;
  control._options = props;

  useSubscribe({
    subject: control._subjects.state,
    next: (
      value: Partial<FormState<TFieldValues>> & { name?: InternalFieldName },
    ) => {
      if (
        shouldRenderFormState(

Review comment (suggestion):
```suggestion
    errors: props.errors || {},
```

Code after:
 * ```
 */
export function useForm<
  TFieldValues extends FieldValues = FieldValues,
  TContext = any,
  TTransformedValues extends FieldValues | undefined = undefined,
>(
  props: UseFormProps<TFieldValues, TContext> = {},
): UseFormReturn<TFieldValues, TContext, TTransformedValues> {
  const _formControl = React.useRef<
    UseFormReturn<TFieldValues, TContext, TTransformedValues> | undefined
  >();
  const _values = React.useRef<typeof props.values>();
  const [formState, updateFormState] = React.useState<FormState<TFieldValues>>({
    isDirty: false,
    isValidating: false,
    isLoading: isFunction(props.defaultValues),
    isSubmitted: false,
    isSubmitting: false,
    isSubmitSuccessful: false,
    isValid: false,
    submitCount: 0,
    dirtyFields: {},
    touchedFields: {},
    errors: props.errors || {},
    disabled: false,
    defaultValues: isFunction(props.defaultValues)
      ? undefined
      : props.defaultValues,
  });

  if (!_formControl.current) {
    _formControl.current = {
      ...createFormControl(props, () =>
        updateFormState((formState) => ({ ...formState })),
      ),
      formState,
    };
  }

  const control = _formControl.current.control;
  control._options = props;

  useSubscribe({
    subject: control._subjects.state,
    next: (
      value: Partial<FormState<TFieldValues>> & { name?: InternalFieldName },
    ) => {
      if (
        shouldRenderFormState(
          value,