[英]Call a static method of a class from a generic class
我正在使用denodb ,一个 ORM 用于deno
。 与 ORM 中的往常一样,模型具有一些 static 方法,例如: get
、 find
等。您可以通过创建从 ORM 提供的通用类扩展的类来定义模型。 在这种情况下:
import { Model } from "https://raw.githubusercontent.com/eveningkid/denodb/master/mod.ts"
class MyModel extends Model {
static table = "energy_meter";
static fields = {
id: { primaryKey: true, autoIncrement: true },
someattribute: DataTypes.STRING,
};
}
这很好用。 我的问题如下:我正在尝试为大量以相同方式访问的模型创建通用数据访问(这就是我使用通用类的原因)。 为了实现这一点,我使用了以下 class:
import { Model } from "https://raw.githubusercontent.com/eveningkid/denodb/master/mod.ts";
export abstract class InventoryDataAccess<E> {
constructor(public model: Model) {}
async get(id: number) {
return ((await this.model.where("id", id).all())[0] as unknown) as E;
}
async getAll() {
return ((await this.model.all()) as unknown) as E[];
}
}
如您所见,这不起作用,因为model
属性是一个实例,而get
方法是 static。 实际消息:
This expression is not callable.
No constituent of type 'Function | FieldValue' is callable.
那是因为get
不是实例方法,所以它试图找到一个可调用的等价物,但没有找到。 这是 model 的实现。
所以我要做的是:调用 class 的 static 方法,我需要将其作为变量传递给InventoryDataAccess
class。
这甚至可能吗? 对于 typescript 中的这种情况,是否有其他方法可以进行通用数据访问?
我找到了以下解决方法:
class A {
public static staticMethod() {
console.log("It works!");
}
}
class B extends A {}
class C {
constructor(public clase: typeof A) {};
test() {
this.clase.staticMethod();
}
}
const c = new C(B);
c.test();
我不相信这目前在 typescript 中是可能的。 正如您所指出的,您不能在实例上下文中调用 static 方法。 此外,static 成员不能与通用 class 的类型参数交互。 Here is a feature request for this, which might enable you to create a generic data access class with a static property on it, if it was implemented in a future version of typescript: https://github.com/microsoft/TypeScript/issues /34665
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.