Classes: The Architect's Blueprint

Classes: The Architect's Blueprint in TypeScript: An iron foundry does not carve each part it sells from scratch.

The Analogy: The Pattern Shop at an Iron Foundry

An iron foundry does not carve each part it sells from scratch. In a room off the shop floor sits the pattern shop, where a joiner makes a wooden pattern: a shaped former that is the exact size of the finished part, plus a little for shrinkage. The pattern is not a part and can never be sold as one. It is pressed into a box of damp sand to leave a cavity, and when molten iron is poured into that cavity and cooled, out comes a casting: one real part, in metal, shaped by the pattern. A class is the pattern, and each object you build from it is a casting.

The pattern carries the shape and nothing else; the metal that fills each casting is the casting's own. Two castings from one pattern are the same shape but separate lumps of iron, so grinding a flat on one leaves the other untouched. In the same way, a class describes the fields and methods every object will have, and each object built from it holds its own copy of those fields. Constructing an object is the pour: the constructor is the boxing-up procedure that runs once per casting to fill the cavities, so that the moment the casting leaves the mould its fields already hold their starting values.

The pattern maker builds three kinds of feature into the pattern. There are the finished outer faces the customer inspects and machines, which anyone may touch: those are the public members. There are internal cored cavities that give the part its strength but never appear on the customer's drawing, sealed away inside the casting: those are the private fields, reachable only by the part's own machined ports. And there are core prints, the register marks the pattern maker shares with the apprentices who build the derived patterns for a bigger assembly: those are the protected members, visible to the pattern and its descendants but not to an outside buyer. A serial number struck into the metal at the pour and never re-cut is a readonly field: set once, fixed for the life of the part.

The failure mode is trying to ship the pattern itself as though it were a part, or pouring a casting without following the boxing procedure. A pattern handed to a customer is useless: it is wood, not iron, and has none of a real part's metal. That is the error of using a class where you needed an instance. Worse is a casting poured before the sand was properly rammed and the cavities filled: it comes out with hollow voids where solid metal should be, and it snaps the first time it is loaded. That is an object whose fields were never set because the constructor's work was skipped, and it fails the moment a method reads a field that holds nothing.


Syntax or Core Structure

A class declares its fields, a constructor that runs once when you write new, and methods that every instance can call. Each instance keeps its own field values, so changing one does not touch another.

// src/counter.ts
class Counter {
    private count = 0;
    constructor(private step: number) {}
    tick(): void {
        this.count += this.step;
    }
    value(): number {
        return this.count;
    }
}

const c = new Counter(5);
c.tick();
c.tick();

const d = new Counter(3);
d.tick();

console.log(c.value());
console.log(d.value());
console.log(c.value());

Output:

10
3
10

c is built with a step of 5; two tick calls raise its private count to 10. d is a separate instance built with a step of 3; one tick raises its own count to 3. The two objects share the pattern but not the metal, so d's single tick leaves c untouched: the last line reads c.value() again and still prints 10. The count field is private, so it can be reached only through the methods the class exposes.


Technical Depth: Fields, Shorthand, readonly, and Inheritance

A class can declare its fields the long way or through the constructor shorthand, freeze a field with readonly, and extend another class with super to reuse a base.

Fields, the constructor, and this

The explicit form declares each field, then assigns it in the constructor. Inside a method, this refers to the instance the method was called on, so it reaches that instance's own fields.

// src/gate.ts
class Gate {
    label: string;
    private open: boolean;
    constructor(label: string) {
        this.label = label;
        this.open = false;
    }
    toggle(): string {
        this.open = !this.open;
        return this.label + ": " + (this.open ? "open" : "shut");
    }
}

const g = new Gate("north");
console.log(g.toggle());
console.log(g.toggle());

Output:

north: open
north: shut

The constructor sets label to "north" and open to false when g is built. The first toggle flips open to true and returns "north: open"; the second flips it back and returns "north: shut". Both reads of this.label reach g's own label, and open is private, changed only from inside the class.

Parameter properties: the constructor shorthand

Prefixing a constructor parameter with an access modifier declares and assigns the field in one stroke. The two classes below are equivalent, but the shorthand removes the repetition of naming each field three times.

// src/point.ts
class Point {
    constructor(public x: number, public y: number) {}
    move(dx: number, dy: number): Point {
        return new Point(this.x + dx, this.y + dy);
    }
    show(): string {
        return this.x + "," + this.y;
    }
}

const p = new Point(2, 3).move(4, 1);
console.log(p.show());

Output:

6,4

Writing public x: number in the parameter list declares a field x and assigns the argument to it automatically, so there is no separate x: number; line and no this.x = x;. The chain builds a Point at (2, 3), then move(4, 1) returns a fresh Point at (2 + 4, 3 + 1), which is (6, 4), and show prints "6,4". The original point is untouched because move returns a new instance rather than mutating.

readonly fields

A readonly field may be set in the constructor and never again. The compiler rejects any later assignment, which is how you model an identifier that must not drift after the object is built.

// src/badge.ts
class Badge {
    constructor(public readonly id: string, public holder: string) {}
}

const b = new Badge("B1", "ada");
b.holder = "grace";       // allowed: holder is mutable
// b.id = "B2";           // refused: id is readonly
console.log(b.id + " " + b.holder);

Output:

B1 grace

Output (tsc, for the commented line):

error TS2540: Cannot assign to 'id' because it is a read-only property.

b is built with an id of "B1" and a holder of "ada". Reassigning holder to "grace" is allowed because it is an ordinary mutable field, so the line prints "B1 grace". Uncommenting the b.id = "B2" line would fail to compile with TS2540, because id was marked readonly and can be set only during construction.

Inheritance with extends and super

A class can extend another, inheriting its fields and methods. The subclass constructor must call super before touching this, and a method may call super.method() to reuse the base version.

// src/tools.ts
class Tool {
    constructor(protected name: string) {}
    describe(): string {
        return this.name;
    }
}

class Drill extends Tool {
    constructor(private speed: number) {
        super("drill");
    }
    describe(): string {
        return super.describe() + " at " + this.speed;
    }
}

const t = new Drill(900);
console.log(t.describe());

Output:

drill at 900

Drill extends Tool, so it inherits name and the base describe. Its constructor calls super("drill") first, setting the protected name on the base, then stores its own speed. The overriding describe calls super.describe() to get "drill" from the base and appends " at 900", printing "drill at 900". Because name is protected, the subclass can read it through the base method but an outside caller cannot.

The member kinds at a glance

MemberWhat it is
fieldper-instance data, its own copy in each object
methodshared behaviour every instance can call
constructorthe code that runs once when new is used
parameter propertya constructor parameter that also declares a field
readonly fielda field that can be set only in the constructor

Fields hold the state, methods act on it, the constructor fills it at the pour, and the modifiers decide who may reach it and whether it can change.


Real World Example: A Register of Electricity Meters

A depot tracks the electricity meters on its units. Each meter knows its own identifier and its tariff in pence per unit, keeps a private running count of the units it has recorded, and can report both its reading and its charge. The register builds several meters from one class, records usage against each, and prints a billing report whose charge column sums to the depot's total.

// src/register.ts
class Meter {
    private used = 0;
    constructor(public readonly id: string, private rate: number) {}
    record(units: number): void {
        this.used += units;
    }
    reading(): number {
        return this.used;
    }
    charge(): number {
        return this.used * this.rate;
    }
}

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

const meters = [
    new Meter("M1", 12),
    new Meter("M2", 20),
    new Meter("M3", 15),
];

meters[0].record(3);
meters[0].record(2);
meters[1].record(4);
meters[2].record(6);

const rows: string[] = [];
let total = 0;
for (const m of meters) {
    const due = m.charge();
    total += due;
    rows.push(pad(m.id, 6) + pad(String(m.reading()), 8) + String(due));
}

const report = [
    "meters: " + meters.length,
    pad("METER", 6) + pad("UNITS", 8) + "CHARGE",
    ...rows,
    "total: " + total,
];
console.log(report.join("\n"));

Output:

meters: 3
METER UNITS   CHARGE
M1    5       60
M2    4       80
M3    6       90
total: 230

Three meters are built from one Meter class, each with its own id, rate, and private used counter. The record calls add usage to the right instance: M1 receives 3 then 2 for a reading of 5, M2 receives 4, and M3 receives 6. Because used is private, the only way usage enters a meter is through record, and the only way it leaves is through reading and charge -- the cored cavity with machined ports.

Trace the charges against each meter's rate. M1 is 5 * 12, which is 60; M2 is 4 * 20, which is 80; M3 is 6 * 15, which is 90. The report loop adds each charge to total as it prints the row, so the footer is 60 + 80 + 90, which is 230. The reading column shows each meter's own used count, confirming the three instances never shared state.

The design has real limits worth naming. The sharpest flaw is that record accepts any number, including a negative one, so a mistyped correction can silently lower a meter's reading below a figure already billed -- yet a real electricity meter is monotonic and can only ever count up. A sturdier class would reject a negative units in record, or model corrections as a separate audited operation. The second limit is that rate is a bare number of pence with no unit type, so a caller who enters a tariff in pounds by mistake gets a charge a hundred times too small with no compile error to catch it; a branded currency type would make the mistake impossible. The class encapsulates its state cleanly, but encapsulation guards who may change a field, not whether the change makes physical sense.


Common Mistakes

  1. Forgetting new when constructing. Calling Meter("M1", 12) without new does not build an instance; under strict the compiler rejects it, and in plain JavaScript it would run the constructor with the wrong this. Always write new to pour a fresh object.
  1. Reading a field before the constructor sets it. A field left unassigned in the constructor holds undefined, and a method that reads it behaves like a casting with a hollow void. Initialise every field, either at declaration or in the constructor.
  1. Mixing the shorthand and the long form for one field. Declaring public x: number as a parameter property and also writing a separate x: number; field, or reassigning it manually, duplicates the field and confuses readers. Choose one form per field.
  1. Assigning to a readonly field after construction. A readonly field can be set only in the constructor; a later obj.id = ... fails to compile with TS2540. Model anything that legitimately changes as an ordinary mutable field.
  1. Touching this before calling super in a subclass. A subclass constructor must call super(...) before it reads or writes this, because the base has not run yet. Put the super call first.
  1. Assuming private is enforced at runtime. The private keyword is a compile-time check that is erased in the emitted JavaScript; for true runtime hiding use a #name private field. Do not rely on private to keep a secret from code that ignores the types.
  1. Sharing mutable state through a field on the class rather than the instance. A field initialised once and expected to differ per object must live on the instance, set in the constructor, not be a value shared across every casting from the pattern.
  1. Overusing inheritance for code reuse. Reaching for extends to share a helper couples the subclass to the base's whole shape. Prefer composing a plain object or a function when you only need to reuse behaviour, not to model an is-a relationship.
  1. Making every field public by default. Leaving state public lets any caller mutate it into an invalid combination. Default to private and expose only the methods that keep the object's invariants.

Best Practices

  • Initialise every field at the pour. Assign each field at declaration or in the constructor so no instance ever leaves the mould with a field holding undefined.
  • Prefer parameter properties for plain fields. When a constructor's only job is to store its arguments, the public/private/readonly parameter shorthand removes three repetitions per field and reads more cleanly.
  • Default fields to private and expose methods. Keep state private so the only ways to change it are the methods that enforce the object's rules, the way a casting's cored cavity is reachable only through machined ports.
  • Mark identifiers readonly. Anything that identifies the object for its whole life, such as an id or a serial number, should be readonly so a stray assignment cannot re-cut it.
  • Call super first in a subclass constructor. Run the base constructor before touching this, so the inherited fields exist before the subclass builds on them.
  • Reach for #private when runtime hiding matters. Use a #name field when the secret must survive into the emitted JavaScript, and reserve the private keyword for compile-time discipline.
  • Prefer composition to deep inheritance. Model reuse by holding another object or calling a function rather than stacking extends chains, which couple a subclass to every detail of its base.
  • Validate arguments that must make sense. When a value like a meter reading can only move one way, check it in the method that sets it, because encapsulation controls who writes a field, not whether the written value is sane.

Practice Exercises

  1. The smart device. Write a class Device with a public name and a private on boolean that starts false, plus a toggle method that flips it and returns the new state. Build two devices and show that toggling one does not change the other.
  1. The parameter-property employee. Write a class Employee that uses the constructor shorthand to declare a readonly id, a public name, and a private salary, then add a raise(amount) method and confirm the compiler rejects any assignment to id.
  1. The validated meter. Extend the lesson's Meter so record throws when units is negative, then show that a valid recording still updates the reading while a negative one is refused.
  1. The inherited tool. Write a base class Tool with a protected name and a describe method, extend it with a Saw that adds a teeth field and overrides describe to call super.describe(), and print the result for one saw.