Typescript 从基类静态方法返回子类的新实例
我的困境是: 我想要一个基类,它可以返回其子类的新对象 比如: 现在在我的IndexComponent课上Typescript 从基类静态方法返回子类的新实例,typescript,Typescript,我的困境是: 我想要一个基类,它可以返回其子类的新对象 比如: 现在在我的IndexComponent课上 export class IndexComponent { var user = Child.query() // By this I have a new object of Child class in user variable } 提前谢谢你 解决方案很简单: export class Base { constructor () {} static query
export class IndexComponent {
var user = Child.query() // By this I have a new object of Child class in user variable
}
提前谢谢你 解决方案很简单:
export class Base {
constructor () {}
static query() {
return new this();
}
}
let base = Base.query(); // Base {}
let child = Child.query(); // Child {}
()
这是因为在执行静态函数时,This
是构造函数。您可以在编译的js中看到:
var Base = (function () {
function Base() {
}
Base.query = function () {
return new this();
};
return Base;
}());
query
函数是Base
构造函数的属性,也是Child
的属性,因为它扩展了Base
这里的问题是如何键入此query
函数,以便编译器知道返回的类型。目前,您需要执行以下操作:
let base = Base.query(); // here base is of type 'Base'
let child: Child = Child.query(); // need to declare the type
// or
let child2 = Child.query() as Child; // or assert it
我想不出让编译器推断返回的正确类型的方法,我想知道是否有人有想法。谢谢。我能够安慰孩子们的对象。谢谢你的回答。我也有类似的情况,但我的基类是抽象的,编译器给了我以下错误:
错误TS2511:无法创建抽象类的实例…
。我该怎么处理?如果我删除abstract
关键字,它将正常工作。更多详细信息如下:@slavafomini您可能需要将此
转换为其他内容
let base = Base.query(); // here base is of type 'Base'
let child: Child = Child.query(); // need to declare the type
// or
let child2 = Child.query() as Child; // or assert it