打字稿“这种打字"困惑 [英] Typescript "this-typing" confusion
问题描述
据我所知,使用 this
作为类型是指当前类,或点剩下的任何内容(从而允许继承的方法引用它们自己的类而不是它们父类的类).
It is my understanding that using this
as a type refers to the current class, or whatever is left of the dot (thereby allowing inherited methods to refer to their own class instead of their parent's class).
那么有人可以解释为什么这不起作用:
So can someone explain why this doesn't work:
class Test {
children: Array<this>;
constructor() {
this.children = [new Test()];
}
}
(我的目标是使用继承的类来实现,但它不适用于基类.既然 this
是 Test
类型,为什么不能children
是 Test
的数组吗?
(My goal is to do that with an inherited class, but it doesn't work with a base class. Since this
is of type Test
why can't children
be an array of Test
?
推荐答案
不,当使用 this
作为类型时,您指的是实例而不是类.
它被称为 多态这种类型,意思是像这样使用:
No, when using this
as a type you are referring to the instance and not the class.
It's called Polymorphic this types and is meant to be used like 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
:
If Builder2D.x()
and Builder2D.y()
would have returned 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'
Property 'z' does not exist on type 'Builder2D'
在您的情况下,情况并非如此,您不想返回 this
.
据我所知,this
的类没有类型,但你可以这样做:
In your scenario this isn't the case, you don't want to return this
.
As far as I'm aware there's no type for the class of this
, but you can do:
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".
这篇关于打字稿“这种打字"困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!