是否有方法使用下面描述的方法获得正确的类型。我试过了
使makeInstance()成为泛型,但我尚未获得扩展类型。代码如下。
class Base {
name = 'foo';
static makeInstance() {
return new this();
}
}
class Extended extends Base {
age = 10;
}
let base = Base.makeInstance() // is Base
let extended = Extended.makeInstance(); //should be Extended
console.log(base.name);//ok
console.log(extended.age); //output ok; age doesn't exists
console.log(extended.name);// ok
最佳答案
可以向静态方法添加泛型参数,以推断正确调用该方法的类:
class Base {
name = 'foo';
static makeInstance<T>(this: new () => T) {
return new this();
}
}
class Extended extends Base {
age = 10;
}
let base = Base.makeInstance() // is Base
let extended = Extended.makeInstance(); //is Extended
console.log(base.name);//ok
console.log(extended.age); //ok
console.log(extended.name);// ok
关于typescript - 使用静态方法的 typescript 继承,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51899566/