Exploring the concept of Polymorphic this in TypeScript 1.7, which was brought to my attention in a thoughtful discussion thread I found on Stack Overflow, I came across an interesting way to define methods in a class with a return type of this
. This has the neat benefit of automatically setting the return types of these methods in any extending classes to their respective this
type. Take a look at this code snippet to better understand:
class Model {
save():this { // return type: Model
// Perform save operation and return the current instance
}
}
class SomeModel extends Model {
// inherits the save() method - return type: SomeModel
}
However, my curiosity now leads me to a scenario where I want an inherited static
method to have a return type that references the class itself. The idea is best illustrated through code:
class Model {
static getAll():Model[] {
// Return all instances of Model in an array
}
save():this {
// Perform save operation and return the current instance
}
}
class SomeModel extends Model {
// Inherits the save() method - return type: SomeModel
// Also inherits getAll() - return type: Model (How can we change that to SomeModel?)
}
Considering that Polymorphic this
in TypeScript 1.7 does not support static
methods by design, I might need to explore alternative implementations for this functionality.
EDIT: Keep an eye on the progress of this Github issue here: https://github.com/Microsoft/TypeScript/issues/5863