我正在为我当前的项目编写一个小型模型系统。我希望库的使用者能够向 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;
}
}
我不知道如何在这里完成图案。让工厂吐出正确的实例非常简单,但是 BaseModel
上的 clone
/refresh
之类的操作也需要返回 模型
,而不是any
。
10 月 2 日更新
在尝试 typescript@next(目前技术上是 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();
我在这里打开了一个关于 typescript tracker 的问题: https://github.com/Microsoft/TypeScript/issues/5493
12 月 1 日更新(未解决)
根据 typescript 问题跟踪器,这是不可能的。 “多态 this
”功能仅适用于将排除构造函数的非静态类成员。
最佳答案
您需要使用特殊的this
类型:
class BaseModel {
refresh(): this {
// Refresh returns a new instance, but it should be of
// type Model, not BaseModel.
}
}
在撰写本文时,此功能仅在 TypeScript 的夜间构建中可用(npm install typescript@next
),并将在 TypeScript 1.7 中可用。参见 https://github.com/Microsoft/TypeScript/pull/4910如果你想跟踪特定的提交或阅读更多关于 this
是如何工作的
关于typescript - 在 typescript 中创建一个通用工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33443793/