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
}
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?)
}
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
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…