typescript inheritance using static method

梦想的初衷 提交于 2021-02-07 20:40:41

问题


Is there a way to obtain proper type using approach described below. I have tried make makeInstance() generic but I haven't obtained Extended type. Code below.

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

回答1:


You can add a generic parameter to the static method to infer the class on which the method is invoked correctly :

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


来源:https://stackoverflow.com/questions/51899566/typescript-inheritance-using-static-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!