3.6 Abstract classes

An abstract class is a class that cannot be instantiated, but allow the creation of sub-classes.

Getting Ready

All you need to be able to use abstract classes is an installation of TypeScript version 2.0 or higher.

How to do it…

We can declare an abstract class using the abstract keyword. Note that it is also possible to apply the abstract keyword to some of the methods of the abstract class:

abstract class Base {
  foo(): number { return this.bar(); }
  abstract bar(): number;
}

How it works…

Abstract class cannot be instantiated so if we try to create an instance of the preceding class the TypeScript compiler will throw compilation an error:

const b = new Base;
However, we are allowed to create derived classes from the Base class:
class Derived extends Base {
	bar(): number {
	  return 3;
	}
}

We can then create an instance of the derived class:

const derived = new Derived; // OK
derived.bar(); // 3

The derived class will inherit the non-abstract methods from its base class:

derived.foo(); // 3

Source Code

Abstract classes


Shiv Kushwaha

Author/Programmer