typescript - 类类型,包括静态方法
问题描述
我需要创建一个函数,它将接受一些基类作为参数并返回其他扩展基类的类。
我尝试了以下实现:
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
解决方案
您需要在泛型参数中捕获整个类类型。泛型类型参数可以被约束为构造函数。何时推断泛型类型参数将是整个类,包括静态方法:
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>
推荐阅读
- next.js - NextJS v10 Image 组件在有 basePath 时无法提供图像
- pandas - 按存储在不同列中的复合群组排序
- sql - 一列的默认值可以是SQL中的另一列吗?
- qt - 在一个窗口中显示多个类 QML
- wordpress - 如何在 WP-Rest 上获取类别的 ACF?
- youtube-api - YouTube API 缩略图集端点抛出 403 被禁止
- php - 如何在 PHP 8.0 中键入 Juggle?
- php - phpmyadmin 加载 html 代码而不是普通页面
- c++ - 使用 `altera-struct-pack-align` 的 Clang-tidy 对齐建议
- rust - 将 Box 与 nom 解析器一起使用时出现神秘错误“一种类型比另一种更通用”