我正在为当前项目编写一个小型模型系统。我希望图书馆的消费者能够向API提供他们自己的模型定义。在查询服务器时,API应输出用户模型的实例。在打字稿中创建一个通用工厂(未解决)
// Library Code
interface InstanceConstructor<T extends BaseModel> {
new(): T;
}
class Factory<T extends BaseModel> {
constructor(private cls: InstanceConstructor<T>) {}
get() {
return new this.cls();
}
}
class BaseModel {
refresh() {
// Refresh returns a new instance, but it should be of
// type Model, not BaseModel.
}
}
// User Code
class Model extends BaseModel {
// Custom Model
do() {
return true;
}
}
我无法弄清楚如何在这里完成模式。只是让工厂吐出正确的实例很容易,但/refresh
上的BaseModel
需要也返回Model
,而不是any
。
更新10/2
(此时在技术上1.8 DEV)试图打字稿@接下来我似乎能够得到解决,其中模型可以参考本身(this
)发行及类型后系统可以遵循它。然而,我无法
// Library Code
export interface InstanceConstructor<T extends BaseModel> {
new(fac: Factory<T>): T;
}
export class Factory<T extends BaseModel> {
constructor(private cls: InstanceConstructor<T>) {}
get() {
return new this.cls(this);
}
}
export class BaseModel {
constructor(private fac: Factory<this>) {}
refresh() {
// get returns a new instance, but it should be of
// type Model, not BaseModel.
return this.fac.get();
}
}
// User Code, Custom Model
export class Model extends BaseModel {
do() {
return true;
}
}
// Kinda sucks that Factory cannot infer the "Model" type
let f = new Factory<Model>(Model);
let a = f.get();
let b = a.refresh();
我的打字稿跟踪器在此间开幕的一个问题: https://github.com/Microsoft/TypeScript/issues/5493
更新12/1(未解)
此,根据打字稿问题跟踪器,是不可能的。 “Polymorphic this
”功能仅适用于不包含构造函数的非静态类成员。
不错,现在我知道我需要的名字!我会用TS @接下来尝试一下,谢谢你的提示。 – Xealot