When working with classes and subclasses, it's quite common to define a generic method in the base class, and use the instance specific variable inside it.
However, I can't figure out how to reach the correct static class variable inside methods from the base class.
Take for example the following code:
abstract class Unit<T extends Symbol> {
public static factors: {};
constructor(
protected readonly type: T,
protected value: number
) {}
}
class Energy extends Unit<typeof EnergySym> {
public static factors = {
J: 1,
kJ: 1e3,
MJ: 1e6,
GJ: 1e9,
};
constructor(value: number, unit: keyof typeof Energy.factors = 'J') {
super(EnergySym, value * Energy.factors[unit]);
}
get(unit: keyof typeof Energy.factors) {
return this.value / Energy.factors[unit];
}
}
It would require a lot less code when adding more types of Units, if we can put the get
method inside the base class, by reaching into the static fields of the current class there.
In Python, you can for example use self.__class__.foo
. Is there a JavaScript equivalent?
Additionally, is there a way to add the correct types for that?