TypeScript:继承类中静态方法的自引用返回类型 [英] TypeScript: self-referencing return type for static methods in inheriting classes
问题描述
使用 Polymorphic this 在 TypeScript 1.7 中,正如我发现的那样 这里,我们可以在有返回类型的类中定义方法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 中的多态 this
不支持 static
方法设计em>.
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.
编辑:我想我们会看到这个 Github 问题是如何结束的:https://github.com/Microsoft/TypeScript/issues/5863
EDIT: I guess we'll see how this Github issue wraps up: https://github.com/Microsoft/TypeScript/issues/5863
推荐答案
这在 TypeScript 2.0+ 中是可行的.通过使用内联 { new(): T }
类型来捕获 this
,你会得到你想要的:
This is doable in TypeScript 2.0+. By using an inline { new(): T }
type to capture this
, you'll get what you wanted:
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 | undefined {
return // dummy impl
}
save(): this {
return this // dummy impl
}
}
class SubModel extends BaseModel {}
const sub = new SubModel()
const savedSub: SubModel = sub.save()
// Behold: SubModel.getAll() returns SubModels, not BaseModel
const savedSubs: SubModel[] = SubModel.getAll()
请注意,getAll
仍然不希望使用这种类型的参数.
Note that getAll
still expects no arguments with this typing.
有关更多信息,请参阅https://www.typescriptlang.org/docs/handbook/2/generics.html#using-class-types-in-generics 和 https://stackoverflow.com/a/45262288/1268016
For more information, see https://www.typescriptlang.org/docs/handbook/2/generics.html#using-class-types-in-generics and https://stackoverflow.com/a/45262288/1268016
这篇关于TypeScript:继承类中静态方法的自引用返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!