What is the process for calling a recursive constructor in TypeScript?

I am working on a class constructor overload where I need to recursively invoke the constructor based on the provided arguments.

class Matrix {
    /**
     * Construct a new Matrix using the given entries.
     * @param   arr the matrix entries
     */
    constructor(arr?: number[][]);

    /**
     * Construct a new Matrix with specified size.
     * @param   rows the number of rows in the matrix
     * @param   cols the number of columns in the matrix
     */
    constructor(rows?: number, cols?: number);

    constructor(rows: number[][]|number = 0, cols: number = 0) {
        function isMatrixRaw(m: any): m is number[][] {
            // validate if m is a 2D array of numbers
        }
        if (isMatrixRaw(rows)) {
            // perform main operations here
        } else { 
            let m: number[][];
            // create a 2D array based on rows and cols
            // make a recursive call to the constructor with the new 2D array
            new Matrix(m) // Is this correct?
        }
    }
}

The primary task of the constructor is completed when the argument is a 2-dimensional array of entries. However, an additional overload is needed for providing row and column sizes (e.g., new Matrix(2,3)). If both rows and cols are numbers, I intend to generate a 2-dimensional array and then pass it back into the constructor.

How do recursive constructor calls function in TypeScript? Should I use new Matrix(), return new Matrix(), this.constructor(), Matrix.constructor(), or another approach?

Answer №1

You have the option to return a value from the constructor, which will then be the result of the `new` operation:

class Matrix {
    public rows: number[][];
    constructor(arr: number[][]);
    constructor(rows: number, cols: number);
    constructor(rows: number[][]|number = 0, cols: number = 0) {
        function isMatrixRaw(m: any): m is number[][] { return m instanceof Array; }
        if (!isMatrixRaw(rows)) {
            // Initialize rows with an array
            rows = new Array(rows).fill(0).map(_ => new Array(cols).fill(0));
            return new Matrix(rows);
        } else {
            this.rows = rows; // Now it's definitely a number[][]
        }
    }
}

If possible, consider restructuring your code so that this additional call is not required. Perform the check first and then carry out the main tasks in your constructor as if it were called with `number[][]` initially.

class Matrix {
    public rows: number[][];
    constructor(arr: number[][]);
    constructor(rows: number, cols: number);
    constructor(rows: number[][]|number = 0, cols: number = 0) {
        function isMatrixRaw(m: any): m is number[][] { return m instanceof Array; }
        if (!isMatrixRaw(rows)) {
            // Initialize rows with an array
            rows = new Array(rows).fill(0).map(_ => new Array(cols).fill(0));
        }
        this.rows = rows; // Now it's definitely a number[][]
    }
}

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

Setting a variable based on the stage of its deployment in a DevOps environment: What you need to know

Is there a way I can easily update a variable in a React app based on the stage of an Azure DevOps release pipeline? For instance, if I have dev, QA, and production stages set up, and I want to change the client ID in the auth configuration for each envi ...

Is Typescript syntax for a collection of strings comparable to using string[]?

When working with Typescript, the convention to define an Array of Strings is either string[] or Array<string>. In our team, we lean towards using the more concise string[]. However, when it comes to defining a Set of Strings, is there a shorter syn ...

A Error occurs if ReactQuill is used without defining the document object

Recently, I embarked on a journey with both next.js and ReactQuill. However, upon running yarn build, an unexpected obstacle arose: info Creating an optimized production build - info Compiled successfully - info Linting and checking validity of types - in ...

The integration of react-color Saturation with @types/react-color is currently unavailable

In my quest to develop a customized color picker, I am utilizing the react-color library (^2.19.3) together with @types/react-color (^3.0.4). The issue arises when trying to import the Saturation component since it is not exported from the types in the ind ...

Angular 12: How to detect when a browser tab is closing and implement a confirmation dialog with MatDialog

I have a scenario where I am checking if the browser tab is closed using the code below. It currently works with windows dialog, but I would like to incorporate MatDialog for confirmation instead. @HostListener('window:beforeunload', ['$eve ...

Using Bazel, Angular, and SocketIO Version 3 seems to be triggering an error: Uncaught TypeError - XMLHttpRequest is not recognized

Looking to integrate socket.io-client (v3) into my Angular project using Bazel for building and running. Encountering an error in the browser console with the ts_devserver: ERROR Error: Uncaught (in promise): TypeError: XMLHttpRequest is not a constructor ...

Frontend Will Not Be Able to Access Cloud Run Environment Variables when in Production

My current setup involves using docker to build an image through Google Cloud Build and Google Cloud Registry. I have Pub/Sub triggers in place to populate Cloud Run instances with new Docker images upon a successful build. The issue I am facing is that m ...

Checking if the Cursor is Currently Positioned on a Chart Element in Word Addin/OfficeJS

I am looking for a way to determine if the document cursor is currently positioned inside of a Chart element using the Microsoft Word API. My current application can successfully insert text, but when I attempt to insert text into the Chart title, it ends ...

How can I integrate keydown.control with a unique click function in Angular?

Is there a way to choose multiple number elements in random order and save them to an array by holding down the control key (CTRL) and clicking on the element? For example, selecting 2 and 4 out of 5. I tried different methods but couldn't figure out ...

Is it possible for transclusion to display content from external sources using *ngIf and <ng-content>?

In my Angular4 Project, I have come across this snippet of code: <div class="divider"></div> <ng-content select=".nav-toggle"></ng-content> Now, I am trying to figure out a way to display the divider only when there is content pr ...

Exploring Typescript: Uncovering the Secrets of the navigator.connection Property

I am trying to access the NetworkInformation interface by using a simple TypeScript function like the one shown below: private checkNetworkConnection(): void { const connection = Navigator.connection || navigator.mozConnection || navigator.webkitConn ...

Error in TypeScript React component due to prop-types ESLint in React

I'm in the process of setting up a typescript-react-eslint project and I've encountered an eslint error with this boilerplate component: import * as React from "react"; interface ButtonProps { children?: React.ReactNode, onClick?: (e: any) ...

In what way does Typescript connect the type definition of our imports to their actual implementation?

Incorporating libraries typedefinition (.d.ts) files, how does TypeScript establish a connection between the imported item and its corresponding type definition? For instance, if we: npm install @types/chai @types/mocha --save-dev Then in bar.spec.js: ...

Using .map() with a union type of string[] or string[][] results in a syntax error

interface Props { data: string[] | string[][]; } function Component({ data }: Props) { return data.map(v => v); } map() is causing an error: The expression is not callable. Each member of the union type '((callbackfn: (value: string, in ...

Are multiple click events needed for identical buttons?

In my component, there is an HTML structure like this: <div id="catalogo" class="container"> <div class="row"> <div *ngFor="let artista of artistas" class="col-sm" style="mar ...

Examining the sum of values in a recursive manner within a dual tree structure in SQL Server

Apologies for the repeated posting of my question, I am new here and still learning how to ask questions clearly and effectively. Currently, I am working on a recursive view that calculates the sum of values from a double tree structure. Despite research ...

Exploring the power of TypeScript strictNullChecks with array manipulation

My understanding of Typescript's behavior with the compiler option strictNullChecks enabled is not yet complete. It appears that in some cases, Typescript (version 2.4.1) recognizes an item in a string[] as a string, while other times it does not: in ...

Before running any unit tests, I have to address all linting issues as required by ng test

Upon running ng test, the output I receive is as follows: > ng test 24 12 2019 14:20:07.854:WARN [karma]: No captured browser, open http://localhost:9876/ 24 12 2019 14:20:07.860:INFO [karma-server]: Karma v4.4.1 server started at http://0.0.0.0:9876/ ...

The autoimport feature in VScode should consistently use absolute paths, unless the file being imported is located in the same

Objective: I want VScode to automatically import my dependencies using absolute paths, unless the file is located in the same directory. For example: Let's say we have ComponentA and ComponentB in the same directory, but a service in a different dire ...

Leverage the TypeScript compiler's output from a .NET library within a Blazor application by referencing it

I am currently facing an issue with three different levels: Main Issue: I have developed a Blazor WebAssembly (WASM) application that requires JavaScript, but I prefer to use TypeScript. To address this, I have added a tsconfig file and the TypeScript cod ...