首页 > 解决方案 > 如何从父类返回子类的类型?

问题描述

调用父类时new this(),我无法弄清楚如何返回子类的类型,而不是父类。

在下面的示例中,代码运行没有错误,但child.hi()显示为错误,因为childhas typeParent和 not Child

class Parent {  
  static get() {
    return new this();
  }
}

class Child extends Parent {
  hi() {
    console.log('hi!');
  }

  static make() {
    const child = this.get();
    child.hi(); // <-- type error
  }
}

Child.make();

打字稿游乐场链接

标签: typescriptinheritance

解决方案


您可以通过在 get 方法中使用泛型来解决此问题,以便正确解析类型:

static get<T>(this: new () => T) {
    return new this();
}

进行此更改后, Parent.get() 和 Child.get() 都应按预期工作。


推荐阅读