Borislav Hadzhiev
Sat Feb 20 2021·2 min read
Photo by Sam Beasley
Abstract classes in typescript:
new
keyword
to directly instantiate an abstract classinstanceof
checks with classes as opposed to with interfaces.Let's look at a simple example:
abstract class Animal { // no implementation - just the signature abstract type: string; abstract move(): void; // has implementation; breathe() { console.log(`The ${this.type} takes a breath.`); } } // Not permitted to create an instance of an abstract class // const animal = new Animal() class Dog extends Animal { type = 'dog'; move() { console.log('The dog runs.'); } } class Monkey extends Animal { type = 'monkey'; move() { console.log('The monkey jumps.'); } } const dog = new Dog(); // can use the implemented method from the abstract class dog.breathe(); // or the methods for which the child class provides implementation dog.move(); const monkey = new Monkey(); monkey.breathe(); monkey.move();
When we extend an abstract class we are forced to provide implementation for the
abstract
methods or properties, in other words to conform to the signature
enforced by the abstract class.
We also are able to use the implemented by the abstract class method, just in
the way inheritance would normally work, any of the classes that extend animal
get access to the breathe
method defined in inheritance. Notice that in the
breathe
method we make use of an abstract property, in implemented methods in
abstract classes we can make use of any of the abstract
properties or methods,
because we have a guarantee that the child classes will have to implement them.
We can think of abstract properties/methods as - existing in the future, or in other words implemented by some child class.
We use abstract classes
when we want to provide reusable implementation of
some function, but that function might depend on some other functions,
that we can't yet implement, because they are functions that are very specific
to the different child classes that extend the abstract class.
For example we could imagine that the implementation of the move
method could
be very different between the different child classes that extend the abstract
class. However all of the child classes at some future point in time will have a
version of the move
method that conforms to the type specified in the
abstract
class.