javascript - 如何在 typescript 中获取 "this"类型

标签 javascript typescript types typescript-typings typescript-generics

class A {
    method : this = () => this;
}

我想要的是this,用作返回类型,代表当前类,即A的子类a。因此,方法仅返回与该类相同类型的值(不仅仅是基类 A)。

<小时/>

我想我有类似的东西:

class A {
    method : <T extends A> () => T = () => this;
}

但这似乎是多余的。我复制了A。当然有更好的方法来做到这一点吗?..

最佳答案

你差不多明白了,method 属性的类型应该声明为 () => this,而不仅仅是 this。编译器知道当用作类型时,thispolymorphic

class A {
    method : () => this = () => this;
}

class B extends A {

}

const b = new B();

const bb = b.method(); // inferred as const bb: B;

关于javascript - 如何在 typescript 中获取 "this"类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54975370/

相关文章:

angular - 将项目附加到 Angular2 中的可观察数组?

python - switch case 的运行时类型检查

javascript - AngularJS 网站示例项目的 Firebase API 问题

javascript - 在日期 javascript 中添加天数

Angular 4 使用 ES2017(例如 string.prototype.padStart)

types - OpenCL 内核中的自定义类型

python - 将具有混合固有类型的字符串列表转换为固有类型

javascript - 包裹在标签中时会触发后面的单击事件

javascript - jQuery val() 比较

coding-style - 对 TypeScript 的接口(interface)和类编码指南感到困惑