Wednesday, 21 February 2018

Calling abstract classes in TypeScript

Abstraction is an Object Oriented programming concept whereby a class can specify how an inherited class should implement the class itself, including any abstract methods specified.The concept of abstraction is we are hiding the complexity of the implementation from inherited classes and we allow them to implement the functionality themselves . 

Abstraction can be achieved by using the abstract keyword - which can be applied to both classes and methods specified in classes.

Let's take an example of abstract class :

abstract class Warrior {
  readonly name: string;
  public weapon: string;
  constructor(name: string) {
    this.name = name;
  }

  abstract arm(weapon: string): void;
}


If we now attempt to instantiate this class we'll get an error:

const peter = new Warrior('Peter, the Nomad'); // Cannot create an instance of the abstract class 'Warrior'.

Now we need to implement the abstract class then we need to create a subclass and extend it using the extends keyword.

class SuperWarrior extends Warrior {
  constructor(name: string) {
    super(name);
  }
  arm(weapon: string): void {
    console.log(`${this.name} is a super warrior fighting with ${weapon}`);
  }
}


Now we have a subclass we can create our warriors.

const warrior = new SuperWarrior('John, the Nomad');
warrior.arm('lance'); // John, the Nomad is a super warrior fighting with lance



we can also utilise Interfaces and implement them for classes

interface IWarrior {
  name: string;
  weapon: string;
  arm(weapon: string): void;
}
abstract class Warrior implements IWarrior {
  readonly name: string;
  public weapon: string;
  constructor(name: string) {
    this.name = name;
  }

  abstract arm(weapon: string): void;
}

class SuperWarrior extends Warrior {
  constructor(name: string) {
    super(name);
  }
  arm(weapon): void {
    console.log(`${this.name} is a super warrior fighting with ${weapon}`);
  }
}

const warrior: IWarrior = new SuperWarrior('John, the Nomad');
warrior.arm('lance');

Featured post

How to create dynamic schema in mongodb

Sometime what we need in our application is to create mongodb schema for collection and some of our collection schema are same but names are...

Popular Posts