打字稿“这打字”混乱

时间:2016-11-09 01:26:55

标签: typescript this

我指的是“this-typing”引用.text()here

我的理解是,使用this作为类型引用当前类或者点的任何剩余(从而允许继承的方法引用它们自己的类而不是它们的父类)。

有人可以解释为什么这不起作用:

class Test {
    children: Array<this>;

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

(我的目标是使用继承的类来执行此操作,但它不适用于基类。由于this的类型为Test,为什么不能children为一个Test

的数组

2 个答案:

答案 0 :(得分:3)

不,当使用this作为类型时,您指的是实例,而不是类 它被称为Polymorphic this types,意思是这样使用:

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();

code in playground

如果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();

使用:

  

'Builder2D'

类型中不存在属性'z'

在您的方案中情况并非如此,您不想返回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

code in playground

修改

似乎存在问题:Polymorphic "this" for static members

答案 1 :(得分:1)

让我们定义派生类:

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

正如您已经指出的那样 - this作为类型引用当前类,因此children成员TestDerived的类型为TestDerived[]。所以我们可以这样做:

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

如果typescript允许我们使用Test的实例填充此数组(在super的构造函数中),我们将失去类型安全性(someMethod中未定义Test)。< / p>

相关问题