如何在TypeScript中调用递归构造函数?

时间:2018-12-30 16:24:08

标签: typescript recursion constructor overloading constructor-overloading

我有一个类构造函数重载,我想根据提供的参数递归调用构造函数。

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

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

    constructor(rows: number[][]|number = 0, cols: number = 0) {
        function isMatrixRaw(m: any): m is number[][] {
            // return `true` if m is of type number[][]
        }
        if (isMatrixRaw(rows)) {
            // ...
            // do all the main work here
            // ...
        } else { // typeof rows === 'number' && typeof cols === 'number'
            let m: number[][];
            // ...
            // create a 2D array of numbers, given rows and cols
            // recursively call the constructor with the new 2D array
            // ...
            new Matrix(m) // <-- is this right?
        }
    }
}

如果参数是条目的二维数组,则完成主要构造函数的工作,但我也想重载:提供行大小和列大小(例如new Matrix(2,3))。如果rowscols是数字,我想创建一个二维数组,然后将该新数组传递回构造函数。

递归构造函数调用在TypeScript中如何工作?我该打电话给new Matrix()return new Matrix()this.constructor()Matrix.constructor()还是其他电话吗?

1 个答案:

答案 0 :(得分:1)

您可以从构造函数中返回一个值。返回的值将是new操作的结果:

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)) {
            // init rows with an array
            rows = new Array(rows).fill(0).map(_ => new Array(cols).fill(0));
            return new Matrix(rows);
        } else {
            this.rows = rows; // it's a number[][] now for sure
        }
    }
}

您可能会考虑重新组织代码,因此不需要进行此额外的调用。只需先进行检查,然后完成构造函数的大部分工作,就好像使用number[][]

进行了调用一样
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)) {
            // init rows with an array
            rows = new Array(rows).fill(0).map(_ => new Array(cols).fill(0));
        }
        this.rows = rows; // it's a number[][] now for sure
    }
}