Typescript "this typical" confusion

I mean the "this-typing" link here , and.

I understand that using thisas type refers to the current class or what is left of the dot (thereby allowing inherited methods to refer to its own class instead of its parent class).

So can someone explain why this is not working:

class Test {
    children: Array<this>;

    constructor() {
        this.children = [new Test()];
    }
}

(My goal is to do this with an inherited class, but it does not work with the base class. Since it thishas a type Test, why childrencan't it be an arrayTest

+4
source share
2 answers

, this , .
" " :

class Point {}

class Point2D extends Point {
    constructor(public x: number, public y: number) {
        super();
    }
}

class Point3D extends Point2D {
    constructor(x: number, y: number, public z: number) {
        super(x, y);
    }
}

class Builder2D {
    protected _x: number;
    protected _y: number;

    x(x: number): this {
        this._x = x;
        return this;
    }

    y(y: number): this {
        this._y = y;
        return this;
    }

    build(): Point {
        return new Point2D(this._x, this._y);
    }
}

class Builder3D extends Builder2D {
    private _z: number;

    z(z: number): this {
        this._z = z;
        return this;
    }

    build(): Point3D {
        return new Point3D(this._x, this._y, this._z);
    }
}

let p1 = new Builder3D().x(0).y(0).z(0).build();

( )

Builder2D.x() Builder2D.y() Builder2D:

x(x: number): Builder2D {
    this._x = x;
    return this;
}

y(y: number): Builder2D {
    this._y = y;
    return this;
}

:

let p1 = new Builder3D().x(0).y(0).z(0).build();

'z' 'Builder2D'

, this.
, this, :

class Test {
    public children: Array<Test>;

    constructor() {
        this.children = [new Test()];
    }
}

interface OtherTest {
    children: Array<OtherTest>;
}
class OtherTest extends Test {
    constructor() {
        super();
        this.children.push(new Test(), new OtherTest());
    }
}

let t1 = new Test();
let c1 = t1.children[0]; // typeof c1 is Test

let t2 = new OtherTest();
let c2 = t2.children[0]; // typeof c2 is OtherTest

( )


, : "this" .

+3

:

class TestDerived extends Test {
    someMethod():void { }
}

- this, , children TestDerived TestDerived[]. - :

let b = new TestDerived ();
b.children[0].someMethod();

typescript ( ) Test, (someMethod Test).

+1

Source: https://habr.com/ru/post/1660251/


All Articles