我被困在:
我想要一个可以返回其子类的新对象的基类。
喜欢:
export class Base {
constructor () {
}
static query() {
//return a new object of class from which this function is called.
}
}
export class Child extends Base {
}
Run Code Online (Sandbox Code Playgroud)
现在在我的 IndexComponent 类中
export class IndexComponent {
var user = Child.query() // By this I have a new object of Child class in user variable
}
Run Code Online (Sandbox Code Playgroud)
先感谢您!
解决方法很简单:
export class Base {
constructor () {}
static query() {
return new this();
}
}
let base = Base.query(); // Base {}
let child = Child.query(); // Child {}
Run Code Online (Sandbox Code Playgroud)
(操场上的代码)
这是有效的,因为在执行静态函数时,this它是构造函数。
你可以在编译后的js中看到:
var Base = (function () {
function Base() {
}
Base.query = function () {
return new this();
};
return Base;
}());
Run Code Online (Sandbox Code Playgroud)
该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
Run Code Online (Sandbox Code Playgroud)
我想不出让编译器推断返回的正确类型的方法,很想知道是否有人有想法。
| 归档时间: |
|
| 查看次数: |
1525 次 |
| 最近记录: |