Abstract Classes: The Unfinished Blueprint

Abstract Classes: The Unfinished Blueprint in TypeScript: A coachbuilder who makes specialist vans and minibuses does not start from raw steel.

The Analogy: The Rolling Chassis at a Coachbuilder

A coachbuilder who makes specialist vans and minibuses does not start from raw steel. The vehicle manufacturer supplies a rolling chassis: a frame with the engine, gearbox, wheels, steering, and brakes all fitted and working, but with no body on top. You can push it around the yard and even drive it slowly under its own power, yet it is not a vehicle anyone may register or sell, because it has no cab, no doors, and nowhere for a passenger to sit. The coachbuilder's job is to build the body onto the running gear the manufacturer already finished. An abstract class is that rolling chassis: the shared running gear is complete and inherited, while the body is deliberately left for each subclass to supply.

The chassis fixes everything the vehicles built on it have in common. The wheelbase, the engine mounts, the wiring spine: drawn and bolted down once, and every body built on the chassis gets them for free. Those are the concrete methods of the base class, written a single time and inherited by all. The parts left off are stamped on the build sheet as "coachbuilder to fit": the body panels, the seating, the interior. Those are the abstract members, declared as required with no implementation, so that every finished vehicle is forced to supply them before it can leave the works.

The assembly bay also fixes the order of the build. The floor goes on first, then the panels, then the glass, then the trim, then the road test, in that sequence, and the sequence is welded into the process no matter which body is being built. That fixed order calling open steps is the template method: a concrete method on the base that calls the abstract steps in a set order the subclass cannot rearrange. A few of those steps carry a standard default that a subclass may replace, the way every vehicle gets a plain cloth interior unless the customer's order overrides it with leather.

The failure mode is trying to plate and drive the bare rolling chassis as though it were a finished vehicle. It has no body, no doors, nowhere for anyone to sit, so the licensing office refuses it and pushing it onto the public road is dangerous. That is calling new on an abstract class: it is incomplete by design, and the compiler refuses to build one. A subtler danger is the build sheet reaching for a panel before the body has supplied it, such as the road-test step running before the seats are bolted in; in a class this is the base constructor calling an abstract method before the subclass has set its fields, so the step finds a hole where a finished part should be.


Syntax or Core Structure

An abstract class declares some members with bodies and others as abstract with none. A subclass must supply every abstract member, and the base can call them from a concrete method without knowing which subclass will answer.

// src/shape.ts
abstract class Shape {
    constructor(protected readonly kind: string) {}
    abstract area(): number;
    abstract perimeter(): number;
    describe(): string {
        return this.kind + ": area " + this.area() + ", perimeter " + this.perimeter();
    }
}

class Rectangle extends Shape {
    constructor(private w: number, private h: number) {
        super("rectangle");
    }
    area(): number {
        return this.w * this.h;
    }
    perimeter(): number {
        return 2 * (this.w + this.h);
    }
}

class Square extends Shape {
    constructor(private side: number) {
        super("square");
    }
    area(): number {
        return this.side * this.side;
    }
    perimeter(): number {
        return 4 * this.side;
    }
}

const shapes: Shape[] = [new Rectangle(3, 4), new Square(5)];
for (const s of shapes) {
    console.log(s.describe());
}
// new Shape("x");   // refused: cannot create an instance of an abstract class

Output:

rectangle: area 12, perimeter 14
square: area 25, perimeter 20

Shape supplies the concrete describe but leaves area and perimeter abstract. The rectangle at 3 by 4 reports an area of 3 * 4, which is 12, and a perimeter of 2 * (3 + 4), which is 14; the square of side 5 reports 5 * 5, which is 25, and 4 * 5, which is 20. describe calls this.area() without knowing which subclass will answer, and the commented new Shape("x") would be refused because an abstract class cannot be built directly.


Technical Depth: Abstract Members, the Template Method, override, and Interfaces

Fields as well as methods can be abstract, a concrete method can fix an algorithm's order around abstract steps, the override keyword catches a broken override, and a table settles when to reach for an abstract class over an interface.

Abstract properties, not just methods

A property can be abstract too, forcing each subclass to supply a value. A concrete helper on the base may then build on both the abstract method and the abstract property.

// src/store.ts
abstract class Store {
    abstract readonly label: string;
    abstract find(id: number): string | null;
    findOrThrow(id: number): string {
        const hit = this.find(id);
        if (hit === null) {
            throw new Error(this.label + ": " + id + " missing");
        }
        return hit;
    }
}

class Rooms extends Store {
    readonly label = "rooms";
    private data: Record<number, string> = { 1: "single", 2: "double" };
    find(id: number): string | null {
        return this.data[id] ?? null;
    }
}

const rooms = new Rooms();
console.log(rooms.findOrThrow(2));
console.log(rooms.find(9));

Output:

double
null

Store declares an abstract label property and an abstract find method, and its concrete findOrThrow uses both. Rooms supplies the label and a find that reads a small table. findOrThrow(2) finds "double" and returns it; find(9) misses the table, so data[9] ?? null yields null, which prints as null. The base needed no knowledge of how Rooms stores its data, only that the abstract members would be supplied.

The template method fixes the order

A concrete method that calls abstract steps in a set sequence is the template method. The order lives in one place on the base, and subclasses fill the steps without rearranging them; a step may carry a default that a subclass overrides.

// src/pipeline.ts
abstract class Pipeline {
    run(input: string): number {
        const rows = this.parse(input);
        const kept = rows.filter((r) => this.isValid(r));
        this.save(kept);
        return kept.length;
    }
    protected abstract parse(input: string): string[];
    protected abstract save(rows: string[]): void;
    protected isValid(row: string): boolean {
        return row.length > 0;
    }
}

class CsvPipeline extends Pipeline {
    protected parse(input: string): string[] {
        return input.split(",");
    }
    protected save(rows: string[]): void {
        console.log("saved " + rows.length);
    }
    protected override isValid(row: string): boolean {
        return row.length > 1;
    }
}

const p = new CsvPipeline();
const n = p.run("ab,c,def,,gh");
console.log("kept " + n);

Output:

saved 3
kept 3

run fixes the order: parse, filter, save, count. CsvPipeline supplies parse and save and overrides the default isValid to keep only rows longer than one character. The input splits into ["ab", "c", "def", "", "gh"]; the override keeps "ab", "def", and "gh" and drops "c" and the empty string, leaving 3. save prints "saved 3" before run returns, and the count 3 prints after. A second pipeline written tomorrow would run the exact same order because it lives only on the base.

The override keyword catches a broken override

Marking an overriding method override tells the compiler to verify a base method of that name exists. With noImplicitOverride on, an override that no longer matches, because the base was renamed, becomes a compile error instead of a method that silently stops being called.

// src/override.ts
class Base {
    greet(): string {
        return "hi";
    }
}

class Child extends Base {
    override greet(): string {
        return "hello";
    }
    // override greett(): string { return "x"; }
    // refused: greett does not override anything in Base
}

const c = new Child();
console.log(c.greet());

Output:

hello

Child.greet carries the override keyword, which the compiler checks against Base.greet, so the call prints "hello". The commented greett would be refused, because no such method exists on Base to override; that check is what turns a silent typo, or a base rename that orphans a subclass method, into an error caught at compile time.

Abstract class or interface

AspectAbstract classInterface
holds implementationyesno
holds state in fieldsyesno, declarations only
emits runtime JavaScriptyesno, fully erased
how many per classone, via extendsmany, via implements
has a constructoryesno

The rule is an interface for a pure contract and an abstract class for a contract plus shared machinery. If you keep copying the same methods into every implementer of an interface, that interface wanted to be an abstract class; if there is no shared code and no state, an abstract class is just an interface that adds weight to the output.


Real World Example: A Billing Base with Per-Tariff Rates

A utility bills several accounts, each on a tariff. Every tariff charges the same way -- a rate per unit plus a fixed standing charge -- but the rate and the standing charge differ. An abstract Tariff fixes the billing formula in one concrete method and leaves the two numbers abstract, so each tariff subclass supplies only what varies. The report bills a batch of accounts and totals the charge column.

// src/billing.ts
abstract class Tariff {
    abstract readonly name: string;
    protected abstract rate(): number;
    protected abstract standing(): number;
    bill(units: number): number {
        return units * this.rate() + this.standing();
    }
}

class Domestic extends Tariff {
    readonly name = "domestic";
    protected rate(): number {
        return 12;
    }
    protected standing(): number {
        return 30;
    }
}

class Business extends Tariff {
    readonly name = "business";
    protected rate(): number {
        return 8;
    }
    protected standing(): number {
        return 100;
    }
}

interface Account {
    ref: string;
    tariff: Tariff;
    units: number;
}

function pad(text: string, width: number): string {
    return text.padEnd(width);
}

const accounts: Account[] = [
    { ref: "A1", tariff: new Domestic(), units: 10 },
    { ref: "B2", tariff: new Business(), units: 20 },
    { ref: "C3", tariff: new Domestic(), units: 5 },
];

const rows: string[] = [];
let total = 0;
for (const acc of accounts) {
    const charge = acc.tariff.bill(acc.units);
    total += charge;
    rows.push(pad(acc.ref, 6) + pad(acc.tariff.name, 10) + pad(String(acc.units), 6) + String(charge));
}

const report = [
    "accounts: " + accounts.length,
    pad("REF", 6) + pad("TARIFF", 10) + pad("UNITS", 6) + "CHARGE",
    ...rows,
    "total: " + total,
];
console.log(report.join("\n"));

Output:

accounts: 3
REF   TARIFF    UNITS CHARGE
A1    domestic  10    150
B2    business  20    260
C3    domestic  5     90
total: 500

The abstract Tariff owns the billing formula once, in bill, and leaves rate and standing abstract so each subclass supplies only its two numbers. Domestic charges 12 per unit with a 30 standing charge, and Business charges 8 with 100. The report loop calls acc.tariff.bill(acc.units) without caring which tariff answers, which is the polymorphism the abstract method makes safe.

Trace the charges through the shared formula. A1 is domestic on 10 units: 10 * 12 + 30, which is 120 + 30, which is 150. B2 is business on 20 units: 20 * 8 + 100, which is 160 + 100, which is 260. C3 is domestic on 5 units: 5 * 12 + 30, which is 60 + 30, which is 90. The charge column sums to 150 + 260 + 90, which is 500, printed in the footer.

The design has real limits worth naming. The sharpest flaw is that the template fixes not just the order but the whole shape of the formula: bill hard-codes units * rate + standing, so a tariff that needs a block structure, such as the first ten units free and the rest at a higher rate, cannot fit and would be forced to override bill outright, defeating the shared base. A template method is a straitjacket that fits only variants that keep the same shape. The second limit is that units is unvalidated, so a negative reading produces a charge below the standing charge with no error, and the rates are bare integers with no unit type, so a tariff entered in pounds rather than pence is undetectable. An abstract base removes duplication among variants that are genuinely alike, but it quietly punishes the first variant that is not.


Common Mistakes

  1. Trying to instantiate the abstract class. new Shape() is refused by design, because the class is deliberately incomplete. If you need a usable default, add a concrete subclass rather than reaching for the abstract base.
  1. Touching this before calling super in a subclass constructor. The base has not run yet, so its fields do not exist. Call super(...) first, then set the subclass's own fields.
  1. Calling an abstract method from the base constructor. At construction time the subclass's fields are not initialised, so the override runs against undefined. Defer the call to a method run after construction instead.
  1. Marking an abstract member private. A private abstract member could never be implemented by a subclass, since private is closed even to subclasses. Abstract members must be protected or public.
  1. Building an abstract class where an interface would do. With no shared implementation and no state, an abstract class is just an interface that emits runtime JavaScript and adds weight. Use an interface for a pure contract.
  1. Stacking deep inheritance chains. Three levels of abstract class is a sign the design wants composition, not more inheritance. Prefer holding a collaborator to extending yet another base.
  1. Omitting the override keyword on an overriding method. Without override and noImplicitOverride, a base rename silently orphans the subclass method and it stops being called with no error. Mark every override.
  1. Assuming the template method's shape fits every variant. A fixed formula or order suits only variants that keep that shape; the first variant that needs a different structure has to override the whole template, which defeats the base.
  1. Giving abstract members loose return types. The base's concrete code depends on the exact shapes the abstract members return, so a vague any or an over-wide union there weakens every method built on top of it.

Best Practices

  • Reach for an abstract class only for a contract plus shared code. When several implementations genuinely share both a contract and machinery, an abstract class fits; when they share only a contract, use an interface.
  • Keep the template method public and its steps protected abstract. Callers see one entry point while subclasses see the hooks, so the algorithm's order stays owned by the base and the variation stays in the subclasses.
  • Enable noImplicitOverride and mark every override. Let the compiler verify that each overriding method still matches a base member, so a rename cannot silently orphan an override.
  • Give abstract members precise types. Type each abstract method and property exactly, because the base's concrete code is built directly on those shapes.
  • Call super before touching this. Run the base constructor first so its fields exist before the subclass builds on them, and never call an abstract method from the base constructor.
  • Name abstract classes for what they are. Call them Shape, Tariff, or Pipeline rather than AbstractShapeBase; the abstractness is a fact about the type, not part of its name.
  • Prefer composition before inheritance. Model shared behaviour by holding a collaborator or calling a function first, and reserve an abstract base for the cases where inheritance genuinely earns its keep.
  • Keep the template's shape general enough for its real variants. Before fixing a formula or order on the base, check that every variant you expect keeps that shape, so the first exception does not have to override the whole template.

Practice Exercises

  1. The unfinished vehicle. Write an abstract class Vehicle with an abstract wheels(): number, an abstract fuel property, and a concrete summary() that uses both, then implement Car and Motorbike and confirm new Vehicle() is refused.
  1. The fixed order. Build an abstract class Report with a concrete generate() that calls abstract title(), abstract body(), and a concrete footer() in that order, write two subclasses, and show that the section order cannot be changed from a subclass.
  1. The override guard. Give a base a method, override it in a subclass with the override keyword, then misspell the overriding name and observe the error noImplicitOverride produces.
  1. The template that does not fit. Extend the lesson's Tariff with a block tariff whose first ten units are free, show that it cannot fit bill's fixed formula, and decide whether to widen the base or split the design.