I am interested in implementing a class-based method in Typescript where a method defined on a base class can access the subclass from which it was called. While this behavior is possible in Python, I have not found an equivalent in Typescript. What would be the best approach to achieve this in Typescript?
Python Example:
In Python, the following example demonstrates what I aim to achieve.
# Base class
class Model:
objects = []
def __init__(self, objId):
self.objId = objId
Model.objects.append(self)
@classmethod
def getById(cls, objId):
# Method accesses subclass using "cls" parameter
objects = [obj for obj in cls.objects if obj.objId == objId]
if len(objects) > 0:
return objects[0]
else:
print("error")
# Subclass
class Foo(Model):
def __init__(self, objId, name):
self.objId = objId
self.name = name
Foo.objects.append(self)
Foo(1, "foo")
Foo(3, "bar")
# Call method on subclass
foo = Foo.getById(1)
bar = Foo.getById(3)
print(foo.name) # outputs "foo"
print(bar.name) # outputs "bar"
Foo.getById(2) # outputs "error"
Typescript (not functioning as intended):
The following example illustrates a rough equivalent in Typescript, but it does not work due to the absence of class methods.
class Model {
static objects: Model[]
id: number
constructor (id) {
this.id = id
Model.objects.push(this);
}
// Here "cls" should refer to the class on which this method is called
static getById (id): cls {
let item = cls.objects.find(obj => obj.id == id);
if (item === undefined) {
console.log("error");
} else {
return item;
}
}
}
class Foo extends Model {
name: string
constructor (id, name) {
super(id);
this.name = name
Foo.objects.push(this);
}
}
new Foo(1, "foo");
new Foo(3, "bar");
// Here cls === Foo
let foo = Foo.getById(1);
let bar = Foo.getById(3);
console.log(foo.name);
console.log(bar.name);
Foo.getById(2)
While this functionality is simple with a single class, I am struggling to find a way to use a method like this for multiple classes without re-declaring it for each one.
Additional Question:
Is there a way to have an "objects" static property on each subclass, typed specifically to that subclass, without manual redeclaration?
class Model {
static objects: Model[]
class Foo extends Model {
static objects: Foo[]
class Bar extends Model {
static objects: Bar[]
I desire this functionality without having to declare the "objects" property separately for each subclass. Is there a solution for achieving this?