How is it that Derived
is perfectly happy to call this.log()
but somehow doesn't know about this.value
? I'd have thought value
would be set before super()
is called?
How can Derived
have a value set by the constructor and still be accessed by this.log()
?
abstract class Base
{
protected abstract map() : void;
constructor()
{
this.map();
}
}
class Derived extends Base
{
constructor(private value : string)
{
super();
}
protected map(): void
{
this.log();
}
log()
{
alert(this.value);
}
}
const derived = new Derived("Hello world"); // Alerts "undefined"
EDIT: To clarify, I'm not asking how to implement an abstract method in general, I'm asking about how can I invoke the concrete method from the constructor of the abstract class that uses a value defined by the constructor of the concrete class without defining the constructor parameter(s) on the abstract class since every concrete instance needs a variety of different types and values which would make the constructor of the abstract class quite absurd.
I also would like to avoid having the consumer of the abstract class having to remember to call map()
, and ideally, the instance of the concrete class should be valid once it's initialized.