Abstract classes and interfaces
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
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"extendsinherits every field and method.- A subclass constructor must call
super(…)before touchingthis— 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”:
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:
error TS4114: This member must have an 'override' modifier because it overrides a member in the base class 'Animal'.Abstract classes
An abstract class is a base class that is incomplete on purpose:
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:
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):
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(): stringalready fitsSerializable;implementsjust 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:
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+superto reuse code,override(withnoImplicitOverride) to replace it safely,abstractto require subclasses to fill gaps,implementsto check a contract — and composition when “has a” fits better than “is a”.
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.
interface Loggable {
toLog(): string;
}
// abstract class Notifier
// EmailNotifier, SmsNotifier
// Send through bothinterface Loggable {
toLog(): string;
}
abstract class Notifier implements Loggable {
readonly name: string;
protected maxLength = 160;
constructor(name: string) {
this.name = name;
}
abstract deliver(to: string, text: string): string;
notify(to: string, message: string): string {
const text = message.trim().slice(0, this.maxLength);
return this.deliver(to, text);
}
toLog(): string {
return `[${this.name}] max ${this.maxLength} chars`;
}
}
class EmailNotifier extends Notifier {
constructor() {
super("email");
}
override deliver(to: string, text: string): string {
return `Email to ${to}: ${text}`;
}
}
class SmsNotifier extends Notifier {
protected override maxLength = 20;
constructor() {
super("sms");
}
override deliver(to: string, text: string): string {
return `SMS to ${to}: ${text}`;
}
}
const notifiers: Notifier[] = [new EmailNotifier(), new SmsNotifier()];
for (const notifier of notifiers) {
console.log(notifier.notify("Asha", " Your order #1001 has shipped and arrives Friday. "));
console.log(notifier.toLog());
}
// @ts-expect-error -- abstract classes can't be instantiated
const broken = new Notifier("x");Summary
class B extends Ainherits A’s members;super(…)calls A’s constructor andsuper.method()its methods.- Mark overriding members with
override;noImplicitOverridemakes that required and catches renamed base methods. - An abstract class can’t be instantiated; its abstract members must be implemented by every subclass.
implements Interfacechecks 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.