0

Let's say I have a base class and a child class. Consider the following example:

class Animal {
  public static type = "any animal";

  public getType() {
    return Animal.type;
  }

  public setType(newType: string) {
    Animal.type = newType;
  }
}

class Dog extends Animal {
  public static type = "dog";
}

As you can see, the base class (Animal in this example) declares the static type property, and provides accessors for it (getType and setType). But the child class (Dog) has overriden that static type property. Let's do a console.log to see what types we get from an instance of each class:

const animal = new Animal();
const dog = new Dog();

console.log(animal.getType()); // any animal
console.log(dog.getType()); // any animal

We got the value of base's class property in both cases. That's because of the Animal.type expression in the accessor declarations.

So, is it possible to use child class for static property referencing without a need to override the accessor methods?

Like in this manner:

public getType() {
    return <ChildClass>.type;
}

If no, are there any useful workarounds I could use instead of overriding the method each time?

  • You could use `this.constructor` instead of `Animal`, but TypeScript won’t understand that… you’d need something like `(this.constructor as typeof Animal)`. If nobody else gets here before I get to a real computer I will post an answer. – jcalz Feb 19 '23 at 16:48
  • `setType` should absolutely not be a method of the instances! It affects all instances, not the one you are calling it on. Really there shouldn't be a setter for the type at all. – Bergi Feb 19 '23 at 17:54

0 Answers0