This page looks best with JavaScript enabled

Abstract classes in Typescript

 ·   ·  ☕ 2 min read

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.

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

Using abstract classes is easy too..

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

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

1
2
3
4
5
6
7
8
9
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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things