utils icon indicating copy to clipboard operation
utils copied to clipboard

An object type that contains `Json` causes a recursive error in conjunction with `Draft`/`WritableDraft` types from Immer

Open mcmire opened this issue 2 years ago • 3 comments

If you have an object type such as:

{
  foo: Json
}

and you use it to change state within an Immer produce callback — such the callback that update in BaseController v2 takes — then you will get an error:

Type instantiation is excessively deep and possibly infinite

This is happening because Json is a recursive type and Draft and WritableDraft trampoline as they recurse through that Json type. There's an open bug report on the Immer issue tracker with a proposed fix that was eventually reverted.

We should work out some way to avoid this.

mcmire avatar Jan 23 '24 21:01 mcmire

Some starting points for tackling the "Type instantiation is excessively deep" error:

  • TypeScript feature - Tail call elimination on conditional types with accumulator strategy: https://devblogs.microsoft.com/typescript/announcing-typescript-4-5/#tailrec-conditional
  • Accumulator strategy example: https://dev.to/tylim88/typescript-loop-tuple-with-length-1000-4kg
  • 0 extends 1 trick for extending tail recursion limit: https://github.com/microsoft/TypeScript/issues/49459

This might not be enough to resolve the issue if the mutual recursion depth is infinite even with tail call elimination.

MajorLift avatar Jan 24 '24 04:01 MajorLift

Might be resolved by TypeScript 5.5: https://github.com/microsoft/TypeScript/pull/57293

MajorLift avatar Feb 23 '24 03:02 MajorLift

I checked the Immer repo and it looks like this problem still exists: https://github.com/immerjs/immer/issues/839

mcmire avatar Oct 28 '24 15:10 mcmire