使用静态方法的打字稿继承

时间:2018-08-17 16:27:34

标签: typescript typescript-types

有没有一种方法可以使用下面描述的方法获得正确的类型。我试过了 使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

1 个答案:

答案 0 :(得分:3)

您可以向静态方法添加通用参数,以推断在其上正确调用该方法的类:

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