react-hook-form: IntelliSense hangs infinitely in VSCode after installing react-hook-form

Version Number

IntelliSense to hang infinitely in VSCode

Codesandbox/Expo snack

7.52.2

Steps to reproduce

  • Install the latest react-hook-form
  • Try triggering IntelliSense autocompletion with control + space (on mac):
import React, { useEffect, [CONTROL + SPACE HERE] } from "react";
  • IntelliSense hangs infinitely: “Loading…”

Expected behaviour

IntelliSense should work.

What browsers are you seeing the problem on?

No response

Relevant log output

No response

Code of Conduct

  • I agree to follow this project’s Code of Conduct

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Reactions: 10
  • Comments: 18

Most upvoted comments

I spent quite a bit of time investigating this after an issue was opened over on Zod: https://github.com/colinhacks/zod/issues/3233

A few takeaways:

This is often user error

There is rarely a reason to be passing a type into useForm that is so wide/deep/recursive as too break the existing Path<> logic in RHF. I think most occurrences of this issue are user error, naively dropping in huge generated types into useForm. You should use Pick/Omit to pare down a complex type something that actually represents the data your form expects.

Depth limit

That said, I think a depth limit might be a good idea. This will save headaches for people who unintentionally pass in huge types, and would allow RHF to handle recursive types pretty elegantly. It would be valuable to get some guidance from maintainers on how they’d like this implemented.

a) The depth limit would need to be exposed to the users via useForm. Perhaps as a field inside TContext? useForm<MyData, { depth: 5 }>(...) Then the depth could get passed along as part of the generics in Control<> and applied when passed into useController/Controller.

b) Default values. You don’t want to break too many existing projects but a default depth of 50 (as in the existing PR #12169) seems high. Hard to imagine any reasonable form with a depth above, say, 10? (In the Zod issue I referenced earlier a depth of 7 was already enough to freeze VS Code.)

c) Removing TraversedTypes logic. Once there is a depth limit in place, there’s less reason to keep the TraversedTypes logic around. The type comparisons (AnyIsEqual<TraversedTypes, V>) are the most expensive part of the Path<> logic by orders of magnitude. If you get rid of it and go “all in” on a depth-based approach RHF is able to generate even large numbers of paths (thousands) very fast.

Another approach: path builder

I have a concept for an alternative approach that may solve the problem more elegantly: a “path builder” pattern. It’s nice because it lets your type logic stay shallow, instead of trying to recursively compute all paths upfront.

You can get a sense of what I mean from my utility library trailhead: https://www.npmjs.com/package/trailhead

import { trailhead } from 'trailhead';

type Data = {
  firstName: string;
  array: string[];
  nest: {
    nest: {
      firstName: string;
    };
  };
  arrayObject: {
    firstName: string;
    lastName: string;
  }[];
};

const test = trailhead<Data>();

console.log(test); // => { __path: [] }
console.log(test.firstName); // => { __path: ["firstName"] }
console.log(test.array[5]); // => { __path: ["array", 5] }
console.log(test.nest.nest.firstName); // => { __path: ["nest", "nest", "firstName"] }
console.log(test.arrayObject); // => { __path: ["arrayObject"] }
console.log(test.arrayObject[5]); // => { __path: ["arrayObject", 5, "firstName"] }
console.log(test.arrayObject[5].firstName); // => { __path: ["arrayObject", 5, "firstName"] }

In the context of RHF, this is the API I’d recommend.

 const { control } = useForm<MyForm>({
    // ...
  });

<Controller 
  // arbitrary depth, works with recursive types
  name={control.path().users[5].projects[5].whatever} 
  render={()=>null}
/>

This .path() method returns a “builder” object that lets build a path progressively using chained dot/index accesses.

  • This has a certain appeal compared to string paths in my opinion.
  • I also makes it unnecessary to “pre-compute” all the paths, as in the current implementation. TypeScript is lazy so it effectively defers the instantiatiation of property types until they are accessed/compared. All that to say, this approach works for types of arbitrary breadth/depth, including recursive types.
  • This builder object can also maintain a statically-typed reference to the initial control as well, which means there would be no need to pass control as a separate prop, it could be inferred via name.

Backwards compatibility

This whole proposal could be done in a backwards compatible way. The name field could be updated to accept either a regular string path or a “path builder” instance. It’s worth noting that this approach requires Proxy (see the implementation of trailhead for an idea of how it works).

I think this approach is complementary to a depth limit as well. A depth limit of ~6 would effectively prevent TS performance issues. Anyone who needs deeper paths could use the path builder.

If the maintainers are interested in this at all I’m happy to put in a PR. We can flesh out details in the PR comments.

Took me 3 days to find this problem. If I remove the type casting from useForm, then it’s fixed. Turns out it takes the entire power of my laptop to define typeof RequestFundsFormSchema.

Unending pain version:

 const {
    register,
    getValues,
    control,
    reset,
    formState: { errors },
    setValue,
    handleSubmit,
  } = useForm<typeof RequestFundsFormSchema>({
    resolver: zodResolver(RequestFundsFormSchema),
    defaultValues: {
      linkExpirySelect: ['1'],
      trustPeriodSelect: ['24'],
      trustPeriod: '24',
      linkExpiry: '1',
      usdAmount: 0,
      amount: 0,
      recipientAddress: address,
      currency: CurrencyType.ETH,
    },
    progressive: true,
  });

Happy and fast version:

  const {
    register,
    getValues,
    control,
    reset,
    formState: { errors },
    setValue,
    handleSubmit,
  } = useForm({
    resolver: zodResolver(RequestFundsFormSchema),
    defaultValues: {
      linkExpirySelect: ['1'],
      trustPeriodSelect: ['24'],
      trustPeriod: '24',
      linkExpiry: '1',
      usdAmount: 0,
      amount: 0,
      recipientAddress: address,
      currency: CurrencyType.ETH,
    },
    progressive: true,
  });

@Rohit10701 I’ve opened a PR, but your can also try applying this patch (tweak DefaultDepth if type checking is too slow or if you get type errors):

diff --git a/dist/types/path/eager.d.ts b/dist/types/path/eager.d.ts
index 164bf4562d6057ecac71243feb1f64845f95daa7..42f7d6648eb5a7f4263938391fcd9bedb55fad38 100644
--- a/dist/types/path/eager.d.ts
+++ b/dist/types/path/eager.d.ts
@@ -1,6 +1,17 @@
 import { FieldValues } from '../fields';
 import { BrowserNativeObject, IsAny, IsEqual, Primitive } from '../utils';
 import { ArrayKey, IsTuple, TupleKeys } from './common';
+/**
+ * The maximum recursion depth for type checking.
+ * Adjust this value to control how deeply nested paths are evaluated.
+ */
+export type MaxDepth = 50;
+export type DefaultDepth = 6;
+/**
+ * Utility type to decrement the depth value.
+ * This is used to limit the recursion in type checking.
+ */
+type DecrementDepth<D extends number> = D extends MaxDepth ? 49 : D extends 49 ? 48 : D extends 48 ? 47 : D extends 47 ? 46 : D extends 46 ? 45 : D extends 45 ? 44 : D extends 44 ? 43 : D extends 43 ? 42 : D extends 42 ? 41 : D extends 41 ? 40 : D extends 40 ? 39 : D extends 39 ? 38 : D extends 38 ? 37 : D extends 37 ? 36 : D extends 36 ? 35 : D extends 35 ? 34 : D extends 34 ? 33 : D extends 33 ? 32 : D extends 32 ? 31 : D extends 31 ? 30 : D extends 30 ? 29 : D extends 29 ? 28 : D extends 28 ? 27 : D extends 27 ? 26 : D extends 26 ? 25 : D extends 25 ? 24 : D extends 24 ? 23 : D extends 23 ? 22 : D extends 22 ? 21 : D extends 21 ? 20 : D extends 20 ? 19 : D extends 19 ? 18 : D extends 18 ? 17 : D extends 17 ? 16 : D extends 16 ? 15 : D extends 15 ? 14 : D extends 14 ? 13 : D extends 13 ? 12 : D extends 12 ? 11 : D extends 11 ? 10 : D extends 10 ? 9 : D extends 9 ? 8 : D extends 8 ? 7 : D extends 7 ? 6 : D extends 6 ? 5 : D extends 5 ? 4 : D extends 4 ? 3 : D extends 3 ? 2 : D extends 2 ? 1 : D extends 1 ? 0 : never;
 /**
  * Helper function to break apart T1 and check if any are equal to T2
  *
@@ -14,17 +25,17 @@ type AnyIsEqual<T1, T2> = T1 extends T2 ? IsEqual<T1, T2> extends true ? true :
  *
  * See {@link Path}
  */
-type PathImpl<K extends string | number, V, TraversedTypes> = V extends Primitive | BrowserNativeObject ? `${K}` : true extends AnyIsEqual<TraversedTypes, V> ? `${K}` : `${K}` | `${K}.${PathInternal<V, TraversedTypes | V>}`;
+type PathImpl<K extends string | number, V, TraversedTypes, Depth extends number> = Depth extends 0 ? never : V extends Primitive | BrowserNativeObject ? `${K}` : true extends AnyIsEqual<TraversedTypes, V> ? `${K}` : `${K}` | `${K}.${PathInternal<V, TraversedTypes | V, DecrementDepth<Depth>>}`;
 /**
  * Helper type for recursively constructing paths through a type.
  * This obscures the internal type param TraversedTypes from exported contract.
  *
  * See {@link Path}
  */
-type PathInternal<T, TraversedTypes = T> = T extends ReadonlyArray<infer V> ? IsTuple<T> extends true ? {
-    [K in TupleKeys<T>]-?: PathImpl<K & string, T[K], TraversedTypes>;
-}[TupleKeys<T>] : PathImpl<ArrayKey, V, TraversedTypes> : {
-    [K in keyof T]-?: PathImpl<K & string, T[K], TraversedTypes>;
+type PathInternal<T, TraversedTypes, Depth extends number> = T extends ReadonlyArray<infer V> ? IsTuple<T> extends true ? {
+    [K in TupleKeys<T>]-?: PathImpl<K & string, T[K], TraversedTypes, Depth>;
+}[TupleKeys<T>] : PathImpl<ArrayKey, V, TraversedTypes, Depth> : {
+    [K in keyof T]-?: PathImpl<K & string, T[K], TraversedTypes, Depth>;
 }[keyof T];
 /**
  * Type which eagerly collects all paths through a type
@@ -34,11 +45,11 @@ type PathInternal<T, TraversedTypes = T> = T extends ReadonlyArray<infer V> ? Is
  * Path<{foo: {bar: string}}> = 'foo' | 'foo.bar'
  * ```
  */
-export type Path<T> = T extends any ? PathInternal<T> : never;
+export type Path<T, D extends number = DefaultDepth> = T extends any ? PathInternal<T, T, D> : never;
 /**
  * See {@link Path}
  */
-export type FieldPath<TFieldValues extends FieldValues> = Path<TFieldValues>;
+export type FieldPath<TFieldValues extends FieldValues, D extends number = DefaultDepth> = Path<TFieldValues, D>;
 /**
  * Helper type for recursively constructing paths through a type.
  * This actually constructs the strings and recurses into nested
@@ -46,17 +57,17 @@ export type FieldPath<TFieldValues extends FieldValues> = Path<TFieldValues>;
  *
  * See {@link ArrayPath}
  */
-type ArrayPathImpl<K extends string | number, V, TraversedTypes> = V extends Primitive | BrowserNativeObject ? IsAny<V> extends true ? string : never : V extends ReadonlyArray<infer U> ? U extends Primitive | BrowserNativeObject ? IsAny<V> extends true ? string : never : true extends AnyIsEqual<TraversedTypes, V> ? never : `${K}` | `${K}.${ArrayPathInternal<V, TraversedTypes | V>}` : true extends AnyIsEqual<TraversedTypes, V> ? never : `${K}.${ArrayPathInternal<V, TraversedTypes | V>}`;
+type ArrayPathImpl<K extends string | number, V, TraversedTypes, Depth extends number> = Depth extends 0 ? never : V extends Primitive | BrowserNativeObject ? IsAny<V> extends true ? string : never : V extends ReadonlyArray<infer U> ? U extends Primitive | BrowserNativeObject ? IsAny<V> extends true ? string : never : true extends AnyIsEqual<TraversedTypes, V> ? never : `${K}` | `${K}.${ArrayPathInternal<V, TraversedTypes | V, DecrementDepth<Depth>>}` : true extends AnyIsEqual<TraversedTypes, V> ? never : `${K}.${ArrayPathInternal<V, TraversedTypes | V, DecrementDepth<Depth>>}`;
 /**
  * Helper type for recursively constructing paths through a type.
  * This obscures the internal type param TraversedTypes from exported contract.
  *
  * See {@link ArrayPath}
  */
-type ArrayPathInternal<T, TraversedTypes = T> = T extends ReadonlyArray<infer V> ? IsTuple<T> extends true ? {
-    [K in TupleKeys<T>]-?: ArrayPathImpl<K & string, T[K], TraversedTypes>;
-}[TupleKeys<T>] : ArrayPathImpl<ArrayKey, V, TraversedTypes> : {
-    [K in keyof T]-?: ArrayPathImpl<K & string, T[K], TraversedTypes>;
+type ArrayPathInternal<T, TraversedTypes, Depth extends number> = T extends ReadonlyArray<infer V> ? IsTuple<T> extends true ? {
+    [K in TupleKeys<T>]-?: ArrayPathImpl<K & string, T[K], TraversedTypes, Depth>;
+}[TupleKeys<T>] : ArrayPathImpl<ArrayKey, V, TraversedTypes, Depth> : {
+    [K in keyof T]-?: ArrayPathImpl<K & string, T[K], TraversedTypes, Depth>;
 }[keyof T];
 /**
  * Type which eagerly collects all paths through a type which point to an array
@@ -67,11 +78,11 @@ type ArrayPathInternal<T, TraversedTypes = T> = T extends ReadonlyArray<infer V>
  * Path<{foo: {bar: string[], baz: number[]}}> = 'foo.bar' | 'foo.baz'
  * ```
  */
-export type ArrayPath<T> = T extends any ? ArrayPathInternal<T> : never;
+export type ArrayPath<T, D extends number = DefaultDepth> = T extends any ? ArrayPathInternal<T, T, D> : never;
 /**
  * See {@link ArrayPath}
  */
-export type FieldArrayPath<TFieldValues extends FieldValues> = ArrayPath<TFieldValues>;
+export type FieldArrayPath<TFieldValues extends FieldValues, TFieldDepth extends number = DefaultDepth> = ArrayPath<TFieldValues, TFieldDepth>;
 /**
  * Type to evaluate the type which the given path points to.
  * @typeParam T - deeply nested type which is indexed by the path
@@ -82,15 +93,15 @@ export type FieldArrayPath<TFieldValues extends FieldValues> = ArrayPath<TFieldV
  * PathValue<[number, string], '1'> = string
  * ```
  */
-export type PathValue<T, P extends Path<T> | ArrayPath<T>> = T extends any ? P extends `${infer K}.${infer R}` ? K extends keyof T ? R extends Path<T[K]> ? PathValue<T[K], R> : never : K extends `${ArrayKey}` ? T extends ReadonlyArray<infer V> ? PathValue<V, R & Path<V>> : never : never : P extends keyof T ? T[P] : P extends `${ArrayKey}` ? T extends ReadonlyArray<infer V> ? V : never : never : never;
+export type PathValue<T, D extends number = DefaultDepth, P extends Path<T, D> | ArrayPath<T, D> = Path<T, D> | ArrayPath<T, D>> = T extends any ? P extends `${infer K}.${infer R}` ? K extends keyof T ? R extends Path<T[K], D> ? PathValue<T[K], D, R> : never : K extends `${ArrayKey}` ? T extends ReadonlyArray<infer V> ? PathValue<V, D, R & Path<V, D>> : never : never : P extends keyof T ? T[P] : P extends `${ArrayKey}` ? T extends ReadonlyArray<infer V> ? V : never : never : never;
 /**
  * See {@link PathValue}
  */
-export type FieldPathValue<TFieldValues extends FieldValues, TFieldPath extends FieldPath<TFieldValues>> = PathValue<TFieldValues, TFieldPath>;
+export type FieldPathValue<TFieldValues extends FieldValues, TFieldDepth extends number, TFieldPath extends FieldPath<TFieldValues, TFieldDepth>> = PathValue<TFieldValues, TFieldDepth, TFieldPath>;
 /**
  * See {@link PathValue}
  */
-export type FieldArrayPathValue<TFieldValues extends FieldValues, TFieldArrayPath extends FieldArrayPath<TFieldValues>> = PathValue<TFieldValues, TFieldArrayPath>;
+export type FieldArrayPathValue<TFieldValues extends FieldValues, TFieldArrayPath extends FieldArrayPath<TFieldValues, TFieldDepth>, TFieldDepth extends number = DefaultDepth> = PathValue<TFieldValues, TFieldDepth, TFieldArrayPath>;
 /**
  * Type to evaluate the type which the given paths point to.
  * @typeParam TFieldValues - field values which are indexed by the paths
@@ -101,8 +112,8 @@ export type FieldArrayPathValue<TFieldValues extends FieldValues, TFieldArrayPat
  *   = [{bar: string}, string]
  * ```
  */
-export type FieldPathValues<TFieldValues extends FieldValues, TPath extends FieldPath<TFieldValues>[] | readonly FieldPath<TFieldValues>[]> = {} & {
-    [K in keyof TPath]: FieldPathValue<TFieldValues, TPath[K] & FieldPath<TFieldValues>>;
+export type FieldPathValues<TFieldValues extends FieldValues, TFieldDepth extends number, TPath extends FieldPath<TFieldValues, TFieldDepth>[] | readonly FieldPath<TFieldValues, TFieldDepth>[]> = {} & {
+    [K in keyof TPath]: FieldPathValue<TFieldValues, TFieldDepth, TPath[K] & FieldPath<TFieldValues, TFieldDepth>>;
 };
 /**
  * Type which eagerly collects all paths through a fieldType that matches a give type
@@ -114,8 +125,8 @@ export type FieldPathValues<TFieldValues extends FieldValues, TPath extends Fiel
  *   = 'foo.bar' | 'baz'
  * ```
  */
-export type FieldPathByValue<TFieldValues extends FieldValues, TValue> = {
-    [Key in FieldPath<TFieldValues>]: FieldPathValue<TFieldValues, Key> extends TValue ? Key : never;
-}[FieldPath<TFieldValues>];
+export type FieldPathByValue<TFieldValues extends FieldValues, TFieldDepth extends number, TValue> = {
+    [Key in FieldPath<TFieldValues, TFieldDepth>]: FieldPathValue<TFieldValues, TFieldDepth, Key> extends TValue ? Key : never;
+}[FieldPath<TFieldValues, TFieldDepth>];
 export {};
 //# sourceMappingURL=eager.d.ts.map

@KKrisu they would need to rewrite the type. Fundamentally the key string || number that supports both indexing and records is flawed and cannot be fixed.

Some have suggested a max depth, but that fails when the breadth gets to large as well since it greedily evaluates the type.

So the issue here is with TSC itself. The type they are using to automagically do the string key is not going to work, intellisense loses it for me when I try a structure like this:

{dog: Array<{item: string}>}

If you try to dog.${0}.item item won’t intellisense for me which makes sense because the type in their system is {number} whereas 0 is 0. You can try to rewrite this with string lits and this will fix this issue.

This is not the first time I’ve encountered this issue in TSC and the problem stems from the recursive type having to build every possible string for every possible key and mixing Array indexes with Object symbol/number/string. Don’t do this.

The real solution is using a method that works with TSC, and that is Lenses/Optics. These don’t give a care about what exists inbetween because you prove it at each step. TSC only has to confirm your path rather than every single path in existence ever for the entire object.

How this would work would be Lens<A, S> instead of “key.that.this”, but the key here is that Lenses can also handle the indexing without losing intellisense since indexing into an Array is special and Lenses treat it as such.

Whereas this type in this library tries to handle every case. Those types are just asking “how sure are you covered every possible type”, throw something exotic in there where there’s no special handling for it and you’ll get the keys of the object now mixed in with all the keys you want and then you end up with breadth and depth of type instantiation.

The issue still persists, has there been any solution till now as this issue not limited only to vscode but the same thing happens with jetbrains fleet and webstorm.

for time being i would just just apply a patch or comment the file in node_modules manually, that’s how i am working rn, it ll mess up some of the type but its not that worse, unless ur project is super complex

checkout how i did it : https://github.com/Rohit10701/tac-form/tree/master/packages/tac-form/patches

@pax-k Thanks for opening this issue, I wouldn’t have found it otherwise, this has been causing me a headache. Last version without this bug as far as I can tell is v7.41.5, was introduced in v7.42.0, just downgraded it while it’s getting fixed.

EDIT: It began giving me Type instantiation is excessively deep and possibly infinite. errors. Turns out I’ve given useForm a type that was too complex to handle. Finally, it got fixed by simplifying my form.