Codectionary / Developer documentation / TypeScript

Abstract Classes

An abstract class cannot be instantiated directly - it exists only to be extended. It can define abstract methods (a signature with no implementation, which subclasses must provide) alongside regular, fully-implemented methods that subclasses inherit as-is. This is TypeScript's way of enforcing a shared contract across a family of related classes.

Syntax

abstract class Name {
  abstract method(): type;
}

Examples

Defining and Extending an Abstract Class

Enforcing that subclasses implement specific methods, while sharing common logic.

abstract class Shape {
  abstract getArea(): number; // no implementation - subclasses MUST provide one

  describe(): string {
    // a concrete method, shared and inherited as-is by every subclass
    return `This shape has an area of ${this.getArea()}`;
  }
}

// const shape = new Shape(); // Error - cannot instantiate an abstract class

class Circle extends Shape {
  constructor(private radius: number) {
    super();
  }
  getArea(): number {
    return Math.PI * this.radius ** 2;
  }
}

const circle = new Circle(5);
console.log(circle.describe());

Best practices

  • Use abstract classes when related classes should share both a common contract (abstract methods) and some actual shared implementation (concrete methods)
  • Use a plain interface instead when you only need to enforce a shape/contract with no shared implementation at all
  • Remember abstract classes can never be instantiated directly - attempting new AbstractClass() is always a compile error
  • Keep abstract method signatures focused and minimal - the fewer methods subclasses are forced to implement, the easier the class family is to extend

At a glance

Purpose
Static types for JavaScript
File extension
.ts ยท .tsx
Runs in
Compiled to JavaScript
Usually used with
JavaScript and its ecosystem

Specifications & further reading

Related TypeScript documentation