typescript max recursion depth restricted to 9 levels

After countless attempts, I finally managed to create a generic type that provides me with all possible combinations of JSON key lists and values. Additionally, I have developed a method to limit the recursion within this type.

type EditAction<T,P extends keyof T,Prev extends any[]> = {
    data : T[P]
    id : [...Prev, P]
    prev : Prev
}

type EditActions<T, Depth extends number = 50, Prev extends any[] = []> = {
    [P in keyof T] : T[P] extends JsonType 
        ? (Prev["length"] extends Depth
            ? EditAction<T,P,Prev>
            : (EditAction<T,P,Prev> | EditActions<T[P],Depth,[...Prev,P]>)) 
        : EditAction<T,P,Prev>
}[keyof T]

Despite implementing a depth limitation, TypeScript throws an error if the depth exceeds 9, leaving me puzzled. It appears that TypeScript's maximum recursion is capped at 50, leading to the following error message:

Type instantiation is excessively deep and possibly infinite.ts(2589)
(property) payload: EditActions<T, 50, []>

Answer №1

To control the depth of recursion, you can apply a method similar to the one used in `lib.es2019.array.d.ts` included with TypeScript.

type FlattenArray<Arr, Depth extends number> = {
    "done": Arr,
    "recur": Arr extends ReadonlyArray<infer InnerArr>
        ? FlattenArray<InnerArr, [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20][Depth]>
        : Arr
}[Depth extends -1 ? "done" : "recur"];

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Defining optional parameters in TypeScript

Currently, I am working on implementing strong typing for a flux framework (specifically Vuex). Here is my current code: const actions = { first(context: Context, payload: string) { return doSomething(context, payload); }, second(context: Context) { r ...

Error encountered in Typescript: The property 'prevUrl' is expected to be present in the props object, but it appears to be missing

When trying to access the props.prevUrl property, the following error is encountered: Property 'prevUrl' does not exist on type '{ nextUrl: string; } | { prevUrl: string; nextUrl: string; } | { prevUrl: string; confirm: () => void; }&apos ...

Tips for creating a custom waitForElementText function in Playwright

I need to implement a function called waitForElementText() in playwright. For example, I have headers labeled with the CSS selector '.header-name' on each page. When navigating from the Home page to the Users page, I provide two parameters to ...

Does this Spread Operator Usage Check Out?

Upon reviewing Angular's API documentation, I came across the declaration for the clone() method in HttpRequest as follows: clone(update: { headers?: HttpHeaders; reportProgress?: boolean; params?: HttpParams; responseType?: "arraybuffer" ...

"Retrieving an element from an array may result in a value of

While going through an array of objects in my Angular component class, I faced a strange issue where the properties kept showing up as undefined. The function responsible for this behavior looks like this: upload(): void { const { fileHandles, related ...

The module ~/assets/images/flags/undefined.png could not be found in the directory

When I use the img tag with a dynamic address filled using require, it works well in the component. However, when I try to write a test for it, an error is thrown. console.error Error: Configuration error: Could not locate module ~/assets/ima ...

Can we incorporate 'this' in the super() constructor?

While reviewing someone else's code, I came across the following snippet: class foo extends bar { constructor() { super(param1, param2, new certainObject(this, otherParams)); } } The issue with this code is that it generates an error ...

Using RxJs in an Angular 2 application to enable row selection in a table by detecting mouse movements

Check out this example of an Angular 2 application with row selection in a table: https://plnkr.co/edit/HdQnWqbg9HloWb4eYGHz. The row selection functionality is implemented using mouse event handlers (mousedown, mousemove, mouseup). Below is the template ...

When utilizing an object as state in React, the `setState` function will only set

Currently, I am working on developing a React form that utilizes a custom Input component which I have created multiple times. The objective is to gather all the names and values from the form in the parent component: {inputName: value, inputName2: valu ...

Securing important code sections in Node/Express using Typescript: A guide

I'm fairly new to the world of JavaScript/Typescript/Node/Express, and as I've been researching, it seems there isn't a universally accepted method for locking critical sections of code in a Node/Express application. I've come across a ...

Identifying Circularity in Dependencies

My current task involves analyzing a dependency tree of "Scenarios" to determine the "weight" of each scenario branch. One important aspect is detecting circular dependencies such as scenario1 -> scenario2 -> scenario3 -> scenario1. At present, ...

React's useState function causes the entire application to crash

Currently, I am working on setting up a basic menu using ASP.net core 2.1, Typescript 3.2.1, material-ui 3.8.3, and React 16.7.0. However, upon running the application, it crashes at the line containing useState showing the error message as TypeError: reac ...

What is the necessity behind keeping makeStyles and createStyles separate in Material UI with TypeScript?

Dealing with TypeScript issues in Material UI has been a frequent task for me, and I find it frustrating that styling components requires combining two different functions to create a hook every time. While I could use a snippet to simplify the process, it ...

Adding a type declaration to the severity property in React Alert - A guide to Typescript

I've developed a type declaration object for the incoming data, but no matter what I try to define as the type for the property "severity", it's not happy. The options it wants (as displayed below) don't seem feasible. I'm curious if th ...

A guide on determining the return type of an overloaded function in TypeScript

Scenario Here is a ts file where I am attempting to include the type annotation GetTokenResponse to the function getToken. import { ConfigService } from '@nestjs/config'; import { google, GoogleApis } from 'googleapis'; import { AppCon ...

Developing Derived Classes in Typescript

I am looking to enhance my service class by creating a subclass where I can define functions with the same name but different implementations. My desired structure is as follows: httpWrapper.get //default is observables. returns observable httpWrapper.pr ...

Tips for obtaining the "inner type" of a particular "instance" in TypeScript's generics

Unable to find more appropriate language to elaborate beyond the title, I'm going to rely on the code itself: let var1 = someExternalLibraryMethod(); // assume var1 is implicitly Promise<string> let var2: typeof var1; // this approach enables ...

Trouble with invoking a function within a function in Ionic2/Angular2

Currently, I am using the Cordova Facebook Plugin to retrieve user information such as name and email, which is functioning correctly. My next step is to insert this data into my own database. Testing the code for posting to the database by creating a func ...

How can I activate TypeScript interface IntelliSense for React projects in VSCode?

Did you know that there are TypeScript interfaces designed for DOM, ES5, and other JavaScript modules? I am curious if it is feasible to have intellisense similar to the one provided by TypeScript Playground for various interfaces in a React project. ...

React Project Encounters NPM Installation Failure

I recently started delving into the world of React and experimenting with different examples. Everything was running smoothly until I attempted to start the server [npm start] and encountered an error as shown below. Despite my best efforts, I can't p ...