Close

TypeScript - Abstract Classes

[Last Updated: Aug 31, 2018]

The instance of an abstract class cannot be created. An abstract thing doesn't exist in reality e.g. a car doesn't exist as a concrete thing but an specialization e.g. Mercedes car does exist.

In TypeScript, an abstract class definition starts with abstract keyword. An abstract class can have method(s) without body; in that case abstract keyword is used in the method signature.

Example

//abstract class
abstract class Shape {
    private _name: string;

    constructor(name: string) {
        this._name = name;
    }

    public draw(): void {
        console.log("pre drawing " + this._name);
        this.drawShape();
    }
   //abstract method
    protected abstract drawShape();
}

class Square extends Shape {
    private _length: number;

    constructor(name: string, length: number) {
        super(name);
        this._length = length;
    }

    //must implement super class abstract methods
    protected drawShape() {
        console.log("drawing square with length "+this._length);
    }
}

//let shape: Shape = new Shape(); error TS2511: Cannot create an instance of an abstract class.

let shape: Shape = new Square("saure", 5 );
shape.draw();

Output

pre drawing saure
drawing square with length 5

The compiled JavaScript code (--target es6):

//abstract class
class Shape {
    constructor(name) {
        this._name = name;
    }
    draw() {
        console.log("pre drawing " + this._name);
        this.drawShape();
    }
}
class Square extends Shape {
    constructor(name, length) {
        super(name);
        this._length = length;
    }
    drawShape() {
        console.log("drawing square with length " + this._length);
    }
}
//let shape: Shape = new Shape(); error TS2511: Cannot create an instance of an abstract class.
let shape = new Square("saure", 5);
shape.draw();

Example Project

Dependencies and Technologies Used:

  • TypeScript 3.0.1
Abstract Class in TypeScript Select All Download
  • typescript-abstract-classes
    • example-abstract-class.ts

    See Also