TypeScript:在继承类中为静态方法自引用返回类型 [英] TypeScript: self-referencing return type for static methods in inheriting classes
问题描述
在TypeScript 1.7中使用 Polymorphic ,因为我发现这里,我们可以在一个返回类中定义一个方法类型的 this
,并且自动地,扩展该类并继承这些方法的任何类将其返回类型设置为它们各自的 this
类型。像这样:
With Polymorphic this in TypeScript 1.7, as I discovered here, we can define a method in a class with a return type of this
, and automatically, any classes that extend that class and inherit the methods, will have their return types set to their respective this
type. Like so:
class Model {
save():this { // return type: Model
// save the current instance and return it
}
}
class SomeModel extends Model {
// inherits the save() method - return type: SomeModel
}
然而,我要做的是继承 static
方法引用类本身的返回类型。最好在代码中描述:
However, what I'm after is to have an inherited static
method with a return type referencing the class itself. It's best described in code:
class Model {
static getAll():Model[] {
// return all recorded instances of Model as an array
}
save():this {
// save the current instance and return it
}
}
class SomeModel extends Model {
// inherits the save() method - return type: SomeModel
// also inherits getAll() - return type: Model (how can we make that SomeModel?)
}
也许我得考虑一下一个不同的方式来实现它,因为TypeScript 1.7中的Polymorphic this
不支持
Perhaps I'll have to think of a different way to implement this, since Polymorphic this
in TypeScript 1.7 does not support static
methods by design.
EDIT: I guess we'll see how this Github issue wraps up: https://github.com/Microsoft/TypeScript/issues/5863
推荐答案
这在T中是可行的ypeScript 2.0+。通过使用内嵌的 {new():T}
类型来捕获这个
,你会得到你想要的:
This is doable in TypeScript 2.0+. By using an inline { new(): T }
type to capture this
, you'll get what you wanted:
class BaseModel {
static getAll<T>(this: { new(): T }): T[] {
return [] // dummy impl
}
save(): this {
return this // dummy impl
}
}
class SubModel extends BaseModel {
}
const sub = new SubModel()
const savedSub: SubModel = sub.save()
const savedSubs: SubModel[] = SubModel.getAll()
请注意, getAll
仍然没有参数。
Note that getAll
still expects no arguments with this typing.
有关更多信息,请参见 https://www.typescriptlang.org/docs/handbook/generics.html#泛型使用类类型和 https://stackoverflow.com/a/45262288/126801 6
For more information, see https://www.typescriptlang.org/docs/handbook/generics.html#using-class-types-in-generics and https://stackoverflow.com/a/45262288/1268016
这篇关于TypeScript:在继承类中为静态方法自引用返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!