I want to be able to use a class-based method in Typescript - i.e. a method defined on a base class which, when called on a subclass, can access the subclass from which it was called. This behaviour is possible in Python, but as far as I can tell there is no equivalent in Typescript. What would be the best way to replicate this in Typescript?
Example (in Python):
This example (written in Python) demonstrates something I may want to do with this.
# Base class
class Model:
objects = []
def __init__(self, objId):
self.objId = objId
Model.objects.append(self)
@classmethod
def getById(cls, objId):
# Method can access 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 working):
This example shows the rough equivalent in typescript, but it doesn't work because of the lack 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)
Clearly this is easy to do with a single class, but I can't figure out a way to be able to use a method like this for multiple classes, without re-declaring it on each one.
Side question:
Is there any way to have an "objects" static property on each subclass, each typed to their subclass, without manually re-declaring it.
class Model {
static objects: Model[]
class Foo extends Model {
static objects: Foo[]
class Bar extends Model {
static objects: Bar[]
Essentially, I want this behaviour, but without having to separately declare the "objects" property on each subclass. Is there any way to do that?