【发布时间】:2020-06-01 16:41:03
【问题描述】:
在打字稿中,可以创建一个基类,该基类具有一个静态函数,子类可以使用该函数并返回调用子类的任何类型。此处显示TypeScript: self-referencing return type for static methods in inheriting classes。
type Constructor<T> = { new (): T }
class BaseModel {
static getAll<T>(this: Constructor<T>): T[] {
return [] // dummy impl
}
/**
* Example of static method with an argument:
*/
static getById<T>(this: Constructor<T>, id: number): T {
return // dummy impl
}
}
class SubModel extends BaseModel {}
const savedSubs: SubModel = SubModel.getById(1234)
如何创建一个接受子类类型输入参数的函数呢?
在伪代码方面,它看起来像这样:
static getByChild<T>(this: Constructor<T>, child: this): T {
return // dummy impl
}
但这不起作用。我怎样才能不可知地使方法参数成为这个基类的子类?
【问题讨论】:
-
请注意,您需要
BaseModel和SubModel中的一些属性,以便它们是 structurally distinct from the empty type,否则您会发现像SubModel.getByChild(1234)这样的奇怪行为正在工作,因为1234 extends {}是真的。
标签: typescript inheritance static