我需要创建一个函数,该函数将接受一些基类作为参数并返回其他扩展基类的类。
我尝试了以下实现:
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
答案 0 :(得分:1)
您需要在通用参数中捕获整个类类型。泛型类型参数可以限制为构造函数。推断时,泛型类型参数将是整个类,包括静态方法:
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>