Abstract classes in Typescript

Why and how of using abstract classes in Typescript.

We have seen a bit of classes and objects in Typescript previously. There was however a key aspect of object oriented programming missing there. Although we discussed inheriting classes, we never mentioned abstract classes.

Sacrilege, that.

On the other hand, anything goes for the daily blogging gobble-gobble.

Abstract classes are meant to be inherited and are not used directly. Defining such an abstract class is painfully easy.

abstract class Planet {
  constructor(public name: string) {
    console.log("abstracted herein:", name);
  }
}

Using abstract classes is easy too..

const planet = new Planet("Pluto");
// error TS2511: Cannot create an instance of an abstract class.

Sorry, wrong code block there. Let me correct that.

class Earth extends Planet {
  constructor() {
    super("earth");
  }
}

const earth = new Earth();
console.log(earth.name);
// earth

Let’s go ahead and throw an abstract method there and see the fun unravel.

abstract class Planet {
  constructor(public name: string) {
    console.log("abstracted herein:", name);
  }

  abstract printLife = () => {
    console.log("everything", 42);
  };
}

class Earth extends Planet {
  constructor() {
    super("earth");
  }

  printLife: () => void;
}

const earth = new Earth();
console.log(earth.name);
console.log(earth.printLife());

/*  earth
    everything 42
    undefined // function doesn't return anything
*/

If you are wondering whatever the hell happened there -

  • Create abstract class
  • Introduce a silly abstract method to console.log something
  • Extend Planet with a class aptly called Earth. Earth must implement the abstract method, else compilation fails
  • Create an instance of the derived class, again aptly named as earth
  • Make everyone reach nirvana by consoling some statements
comments powered by Disqus