Abstract classes and interfaces

Topic 3 of 3 in Classes7 min readIntermediateFree course

Overview

Object-oriented code often has families of related classes: different kinds of notifiers, shapes, payment providers, storage backends. TypeScript gives you two tools for these families. Abstract classes share real code and require subclasses to fill in the gaps. Interfaces with implements describe a contract without any code. Knowing which to use — and when to avoid inheritance altogether — keeps designs simple.

Inheritance: extends and super

TypeScript
class Animal {
  readonly name: string;
  constructor(name: string) {
    this.name = name;
  }
  describe(): string {
    return `${this.name} is an animal`;
  }
}

class Dog extends Animal {
  readonly breed: string;
  constructor(name: string, breed: string) {
    super(name);                 // must run before using `this`
    this.breed = breed;
  }
  override describe(): string {
    return `${super.describe()} — a ${this.breed}`;
  }
}

new Dog("Rex", "beagle").describe();   // "Rex is an animal — a beagle"
  • extends inherits every field and method.
  • A subclass constructor must call super(…) before touching this — TypeScript reports it if you forget.
  • super.describe() calls the parent’s version of a method you’ve overridden.

A Dog can be used wherever an Animal is expected — TypeScript checks that the subclass is compatible with its parent.

override and noImplicitOverride

The override keyword says “this replaces a member of the base class”:

TypeScript
class Dog extends Animal {
  override describ(): string { … }
  // error TS4117: This member cannot have an 'override' modifier because it is not declared in the base class 'Animal'. Did you mean 'describe'?
}

That catches typos — and, more importantly, catches the case where someone renames the base method, leaving your “override” as an unrelated new method. Turn on noImplicitOverride in tsconfig and TypeScript requires override on every overriding member, so this can’t slip through:

Text
error TS4114: This member must have an 'override' modifier because it overrides a member in the base class 'Animal'.

Abstract classes

abstract classes vs implements. abstract class Shape has abstract area(): number with no body, and describe() { … this.area() … } as shared code; it cannot be created with new. Circle and Square extend Shape. interface Serializable has toJSON(): string — a contract only, with no code and no run-time existence; Invoice implements it, and Circle can implement it too. extends: inherit real code from ONE parent class. implements: promise to match one or more interfaces. An abstract class shares code and forces subclasses to fill in the gaps; an interface only describes a shape. Because types are structural, any object with toJSON(): string already fits Serializable — implements just checks it.

An abstract class is a base class that is incomplete on purpose:

TypeScript
abstract class Shape {
  abstract area(): number;              // no body: subclasses must provide it

  describe(): string {                  // shared code that uses the abstract method
    return `${this.constructor.name} with area ${this.area().toFixed(2)}`;
  }
}

class Circle extends Shape {
  readonly radius: number;
  constructor(radius: number) {
    super();
    this.radius = radius;
  }
  override area(): number {
    return Math.PI * this.radius ** 2;
  }
}

new Circle(2).describe();   // "Circle with area 12.57"
new Shape();
// error TS2511: Cannot create an instance of an abstract class.

Forget to implement area in a subclass, and TypeScript reports it:

Text
error TS2515: Non-abstract class 'Square' does not implement inherited abstract member area from class 'Shape'.

This is the template method pattern: the base class defines the overall algorithm (describe, notify, process) and subclasses fill in the steps.

abstract is erased like other modifiers, so abstract classes work fine with Node’s type stripping.

implements: checking against an interface

implements declares that a class matches an interface (or object type alias):

TypeScript
interface Serializable {
  toJSON(): string;
}

class Invoice implements Serializable {
  readonly total: number;
  constructor(total: number) {
    this.total = total;
  }
  toJSON(): string {
    return JSON.stringify({ total: this.total });
  }
}

If Invoice were missing toJSON, the error would appear on the class. A class can implement several interfaces: class Invoice implements Serializable, Printable { … }.

Two things implements does not do:

  • It adds no code and inherits nothing — you still write every member.
  • It doesn’t change the class’s type. Because typing is structural, any object with toJSON(): string already fits Serializable; implements just makes the check happen where the class is declared.

Abstract class or interface?

Use an abstract class when… Use an interface when…
subclasses share real code you only need to describe a shape
there’s a natural single parent a class needs several capabilities
you want protected helpers the implementations are unrelated

Often both: an interface defines the contract (Notifier), and an optional abstract base class provides a convenient starting point.

Prefer composition

Deep class hierarchies (Animal → Mammal → Dog → GuideDog) get rigid quickly: a change near the top ripples through everything. Often it’s simpler to compose objects — give a class the collaborators it needs:

TypeScript
interface Transport {
  send(to: string, text: string): Promise<void>;
}

class Notifier {
  readonly #transport: Transport;
  constructor(transport: Transport) {
    this.#transport = transport;
  }
  notify(to: string, text: string) {
    return this.#transport.send(to, text.trim());
  }
}

const email = new Notifier({ send: async (to, text) => { /* SMTP… */ } });

Here Transport can be any object with a send method — a class, a plain object, or a fake in tests. That flexibility is why TypeScript code tends to favour interfaces and composition, with inheritance kept shallow.

Remember: extends + super to reuse code, override (with noImplicitOverride) to replace it safely, abstract to require subclasses to fill gaps, implements to check a contract — and composition when “has a” fits better than “is a”.

Exercise

A notification system

Write interface Loggable { toLog(): string }. Write an abstract class Notifier implements Loggable with a readonly name, an abstract method deliver(to: string, text: string): string, and a concrete method notify(to: string, message: string): string that trims the message, truncates it to maxLength characters (a protected property, default 160) and returns the result of deliver; plus toLog(). Write EmailNotifier and SmsNotifier that extend it: email delivers Email to x: text; SMS overrides maxLength to 20 and delivers SMS to x: text, and uses the override keyword on both members it overrides. Send one message through an array of Notifiers and print each result and log line. Show with // @ts-expect-error that new Notifier() is rejected.

TypeScript
interface Loggable {
  toLog(): string;
}

// abstract class Notifier

// EmailNotifier, SmsNotifier

// Send through both

Summary

  • class B extends A inherits A’s members; super(…) calls A’s constructor and super.method() its methods.
  • Mark overriding members with override; noImplicitOverride makes that required and catches renamed base methods.
  • An abstract class can’t be instantiated; its abstract members must be implemented by every subclass.
  • implements Interface checks that a class has the interface’s shape — it adds no code.
  • Prefer interfaces and composition for “can do” relationships; use inheritance when subclasses genuinely share implementation.