首页 > 解决方案 > 类类型,包括静态方法

问题描述

我需要创建一个函数,它将接受一些基类作为参数并返回其他扩展基类的类。

我尝试了以下实现:

interface Constructable<T> {
   new (...args: any[]): T;
}

function getClass<T>(_class: Constructable<T>): Constructable<T> {
  // in real app there will be some logic to return different class which extends _class
  return _class;
}

但它不允许我调用返回类的静态方法:

class Class {
  static staticMethod() {}
  instanceMethod() {}
}

const _class = getClass(Class);
_class.staticMethod(); // Property staticMethod does not exist on type Constructable<Class>

(错误staticMethod does not exist on type Constructable<Class>:)

我应该如何修改此函数签名以使其按以下方式工作?

const _class = getClass(Class);

_class.instanceMethod();          // should not be possible
new _class().instanceMethod();    // should be ok
_class.staticMethod();            // should be ok

沙箱:https ://stackblitz.com/edit/typescript-cbhp63

标签: typescriptgenericstypes

解决方案


您需要在泛型参数中捕获整个类类型。泛型类型参数可以被约束为构造函数。何时推断泛型类型参数将是整个类,包括静态方法:

interface Constructable<T> {
    new (...args: any[]): T;
}

function getClass<T extends Constructable<any>>(_class: T) {
     // in real app there will be some logic to return different class which extends _class
    return class extends _class {
        addedMethod() { }
        static addedStaticMethod() {}
    };
}

class Class {
    static staticMethod() {}
    instanceMethod() {}
}

const _class = getClass(Class);
_class.staticMethod(); 
_class.addedStaticMethod();
new _class().addedMethod();
new _class().instanceMethod();

注意:如果您需要实例类型,您可以使用InstanceType<T>


推荐阅读