An abstract is a class with unimplemented methods.

It can’t be instantiated and but an other class can extend it to reuse it’s functionality.

TypeScript Abstract Class Example

abstract class Shape {
constructor(protected name: string) { }

public printName() {
console.log(`I am a ${this.name}`);
}

abstract printPerimeter(): void;
}

class Square extends Shape {
private side: number;

constructor(side: number) {
super('Square');
this.side = side;
}

printPerimeter() {
console.log(`${this.name} has a perimeter of ${this.side * 4}`);
}
}

const square = new Square(10);

square.printName(); // [LOG]: "I am a Square"
square.printPerimeter(); // [LOG]: "Square has a perimeter of 40"

Notes

Available in TypeScript 1.6

Abstract classes in TypeScript require TypeScript 1.6 or above.

The protected keyword

name is protected so it can only be accessed in the base class and the classes inherited from it.

Constructor Shorthand

constructor(protected name: string) { }

is a shorter way of writing

protected name: string;

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

Code Output

Abstract classes produce a JavaScript class as they get transpiled.

The abstract class above results in

class Shape {
constructor(name) {
this.name = name;
}
printName() {
console.log(`I am a ${this.name}`);
}
}

Difference with interfaces

Interfaces have all their members public and abtract.

They do not produce any JavaScript code -> They are only used in TypeScript.

If your abstract class only has abstract and public members, you could consider using an interface instead.