Generic Classes & Interfaces: Reusable Containers

Generic Classes & Interfaces: Reusable Containers in TypeScript: Along the servery of a large canteen stand the plate dispensers: tall steel tubes set into the…

The Analogy: The Spring-Loaded Plate Dispenser in a Canteen

Along the servery of a large canteen stand the plate dispensers: tall steel tubes set into the counter, each with a spring platform inside that rises as plates are lifted off and sinks as they are stacked on. The tube is a fixed piece of engineering -- one bore, one spring rate, one rim at the top -- and it does not care what you load into it. One tube holds dinner plates, the next holds side plates, a third holds soup bowls. The mechanism is standard; the crockery is not. That is a generic class exactly: Dispenser<T> is the tube, machined once, and the T is the label clipped to the front saying what this particular tube is filled with. Dispenser<Plate> and Dispenser<Bowl> share every part of the mechanism and share none of their contents.

The operations the tube offers are few and fixed, and they are the whole point. You can press a plate onto the top and let the spring take it (load), lift the top plate off (serve), and glance at the rim of the topmost plate without lifting it (peek). You can see how high the stack stands. What you cannot do is reach into the middle: it is last-in, first-out, because the spring only ever presents the top. And the tube has a depth -- load past the rim and the plates spill over the top rather than stack, so a well-made dispenser refuses the plate that would overflow it rather than letting it fall.

The canteen has a rack of these tubes, and the supervisor relies on a contract every one of them honours whatever it holds: it will accept a plate, give back the top plate, and report its height. That contract, written down so that the plate tube, the tray tower and the cup chute all satisfy it, is a generic interface -- Store<T>. A supervisor who works only through the contract can drain any dispenser on the rack without knowing or caring what crockery is inside it. And a tube that arrives with no label clipped on is assumed, by standing order, to hold trays -- a default that still fits the mechanism.

The failure mode is forgetting that the tube is blind to its cargo. The spring cannot tell bone china from melamine; once the label is off, nothing in the mechanism knows what it is presenting, so a supervisor who assumes the top plate is a dinner plate and sends it to the carvery, when the tube was quietly refilled with side plates, has caused a fault the tube could never catch. A tube whose label reads "anything at all" -- the any label -- is worse: it still works mechanically, but no line downstream can trust what comes out of it. And you cannot interrogate the tube at the counter for what it is; the type on the label is a note for the people setting up the servery, rubbed off by the time service starts, so if a plate must be sorted by kind at run time, each plate has to carry its own stamp.


Syntax or Core Structure

A generic class writes the type parameter after the class name -- class Dispenser<T> -- and every member may then use T as the element type. The operation that can come up empty returns T | undefined, because an empty tube has nothing to hand back and a signature that pretends otherwise is how a crash reaches production.

// src/dispenser.ts
class Dispenser<T> {
    private items: T[] = [];
    load(item: T): void { this.items.push(item); }
    serve(): T | undefined { return this.items.pop(); }
    peek(): T | undefined { return this.items[this.items.length - 1]; }
    get height(): number { return this.items.length; }
}

const trays = new Dispenser<number>();
trays.load(1);
trays.load(2);
// trays.load("three");   // refused: this tube is labelled number

console.log(trays.height, trays.peek());
console.log(trays.serve(), trays.height);

Output:

2 2
2 1

Output (tsc, for the commented line):

error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.

After two loads the tube holds [1, 2], so height is 2 and peek reads the top without removing it, giving 2 2. Then serve lifts the top plate off and returns it -- 2 -- leaving the height at 1. The commented load is refused before it runs, because the tube is labelled number and a string does not fit. Note serve(): T | undefined: the type says out loud that an empty tube returns nothing, so the caller is made to handle the gap rather than trip over it later.


Technical Depth: The Contract, the Per-Call Type, and What Erases

A generic class rarely stands alone. It implements a generic interface so it can be swapped, it grows methods that carry their own type parameter, and it runs into the one hard rule: the class type parameter does not exist at run time, so no static member and no run-time check may use it.

A generic interface is the contract every tube honours

An interface can be generic too, and a class satisfies it by supplying the type. Code written against the interface -- Store<T> -- works with any implementation, which is what makes the concrete class swappable.

// src/contract.ts
interface Store<T> {
    load(item: T): void;
    serve(): T | undefined;
    get height(): number;
}

class Dispenser<T> implements Store<T> {
    private items: T[] = [];
    load(item: T): void { this.items.push(item); }
    serve(): T | undefined { return this.items.pop(); }
    get height(): number { return this.items.length; }
}

// works against the contract, not the concrete class
function drain<T>(store: Store<T>): T[] {
    const out: T[] = [];
    let plate = store.serve();
    while (plate !== undefined) { out.push(plate); plate = store.serve(); }
    return out;
}

const d = new Dispenser<string>();
d.load("A");
d.load("B");
d.load("C");
const drained = drain(d);
console.log(drained.join(" "));
console.log(d.height);

Output:

C B A
0

drain never names Dispenser; it takes any Store<T> and returns a T[], so the same function empties a tray tower or a cup chute. The tube is last-in first-out, so draining A, B, C yields C B A, and the tube is left at height 0. Program against the interface and the implementation behind it is free to change; program against the class and every caller is nailed to it.

A method may declare its own type parameter

The class parameter T is fixed for the life of an instance. A method that transforms the contents into a different type needs its own parameter, written on the method, fresh for each call.

// src/boxed.ts
class Boxed<T> {
    constructor(public value: T) {}
    map<U>(fn: (value: T) => U): Boxed<U> {   // U is the method's own
        return new Boxed(fn(this.value));
    }
}

const box = new Boxed(5);                       // Boxed<number>, inferred
const mapped = box.map((n) => "n" + String(n)); // Boxed<string>

console.log(box.value, mapped.value);

Output:

5 n5

Boxed<T> fixes T to number the moment new Boxed(5) infers it. The map method introduces U for its result, so it can return a Boxed<string> from a Boxed<number> without the class ever having two parameters. The rule of thumb: put the parameter on the class when the type is a property of the instance, and on the method when it varies per call.

The class parameter does not exist at run time

T belongs to an instance and is erased when the code compiles, so a static member -- shared across every instance and every T -- has no single T to name, and the compiler says so. A static method may declare its own parameter, because that is fresh per call, not per class.

// src/registry.ts
class Registry<T> {
    private items: T[] = [];
    // static latest: T;   // refused: statics cannot see the class T
    add(item: T): void { this.items.push(item); }
    get size(): number { return this.items.length; }
    static of<U>(first: U): Registry<U> {   // a static method's own U is fine
        const r = new Registry<U>();
        r.add(first);
        return r;
    }
}

const r = Registry.of("first");
r.add("second");
console.log(r.size);

Output:

2

Output (tsc, for the commented static field):

error TS2302: Static members cannot reference class type parameters.

Registry.of("first") runs the static factory, which declares its own U, infers it as string, and returns a Registry<string>; one more add brings the size to 2. The commented static field is refused with TS2302, because there is no one T a static could belong to. And because T is gone at run time, you cannot write if (item instanceof T) -- to sort by kind at run time, each item must carry its own stamp, a discriminant field or a validator passed in explicitly.

Where a type parameter can go

The same T can be declared in several places, each with a different scope and lifetime.

PlacementScope of the parameterTypical use
class C<T>the whole instance, fixed at constructiona container's element type
method m<U>()one calltransforming contents to a new type
interface I<T>every implementera swappable contract
static method static f<U>()one calla factory that builds the class
static x: Tnot allowedrefused with TS2302
constructor argumentinfers the class Tnew Boxed(5) gives Boxed<number>

The two rows worth memorising sit together: a static method may carry its own parameter, but a static field may not reference the class one, because the field is shared across all instances and there is no single T for it to be.


Real World Example: The Servery Rack

The servery runs one plate dispenser through a shift and prints the state of the tube at the end: what was offered, loaded, refused and served, what plates remain from the bottom of the tube up, and a tally by kind. The dispenser class is generic and knows nothing of plates -- it is a capacity-bounded Dispenser<T> that could just as well hold cups or tokens -- while the report is written by code that knows this particular tube holds Plates and reads their stamps. The tube refuses any load that would overflow its capacity rather than letting a plate spill.

// src/rack.ts
type Kind = "dinner" | "side" | "bowl";
type Plate = { code: string; kind: Kind; grams: number };
type Op = { op: "load"; plate: Plate } | { op: "serve" };

class Dispenser<T> {
    private items: T[] = [];
    constructor(private capacity: number) {}
    load(item: T): boolean {
        if (this.items.length >= this.capacity) { return false; }
        this.items.push(item);
        return true;
    }
    serve(): T | undefined { return this.items.pop(); }
    peek(): T | undefined { return this.items[this.items.length - 1]; }
    get height(): number { return this.items.length; }
    snapshot(): readonly T[] { return [...this.items]; }   // a copy, not the live array
}

const KIND_ORDER: readonly Kind[] = ["dinner", "side", "bowl"];

const OPS: readonly Op[] = [
    { op: "load", plate: { code: "P1", kind: "dinner", grams: 800 } },
    { op: "load", plate: { code: "P2", kind: "dinner", grams: 800 } },
    { op: "load", plate: { code: "P3", kind: "bowl",   grams: 500 } },
    { op: "serve" },
    { op: "load", plate: { code: "P4", kind: "side",   grams: 300 } },
    { op: "load", plate: { code: "P5", kind: "side",   grams: 300 } },
    { op: "load", plate: { code: "P6", kind: "dinner", grams: 800 } },
    { op: "serve" }
];

function pad(text: string, width: number): string {
    return text.length >= width ? text : text + " ".repeat(width - text.length);
}

function run(capacity: number, ops: readonly Op[]): string {
    const rack = new Dispenser<Plate>(capacity);
    let offered = 0;
    let loaded = 0;
    let rejected = 0;
    let served = 0;
    for (const o of ops) {
        if (o.op === "load") {
            offered += 1;
            if (rack.load(o.plate)) { loaded += 1; } else { rejected += 1; }
        } else if (rack.serve() !== undefined) {
            served += 1;
        }
    }
    const remaining = rack.snapshot();

    const out: string[] = [];
    out.push("offered: " + String(offered) + ", loaded: " + String(loaded)
        + ", rejected: " + String(rejected) + ", served: " + String(served));
    out.push(pad("POS", 5) + pad("CODE", 6) + pad("KIND", 8) + "GRAMS");
    let pos = 0;
    for (const p of remaining) {
        pos += 1;
        out.push(pad(String(pos), 5) + pad(p.code, 6) + pad(p.kind, 8) + String(p.grams));
    }
    const grams = remaining.reduce((sum, p) => sum + p.grams, 0);
    const top = rack.peek();
    const byKind = KIND_ORDER
        .filter((k) => remaining.some((p) => p.kind === k))
        .map((k) => k + " x" + String(remaining.filter((p) => p.kind === k).length));
    out.push("on rack: " + String(remaining.length)
        + ", top: " + (top === undefined ? "none" : top.code + " " + top.kind)
        + ", grams: " + String(grams));
    out.push("by kind: " + byKind.join(", "));
    return out.join("\n");
}

console.log(run(4, OPS));

Output:

offered: 6, loaded: 5, rejected: 1, served: 2
POS  CODE  KIND    GRAMS
1    P1    dinner  800
2    P2    dinner  800
3    P4    side    300
on rack: 3, top: P4 side, grams: 1900
by kind: dinner x2, side x1

Read the shift against the mechanism. Six loads are offered; the tube takes the first five and refuses the sixth, because after P5 the height is 4 and P6 would overflow a capacity of four, so loaded is 5 and rejected is 1. Two serves each lift the current top -- P3 the bowl, then P5 the last side plate -- leaving P1, P2 and P4 in the tube from the bottom up. The Dispenser<T> did none of this reading: it only pushed, popped and reported its height. The report -- the columns of code, kind and grams, the tally by kind -- is written by code that knows this tube is a Dispenser<Plate>, at the one point in the program where T is concrete.

That split is the payoff of the generic class. The same Dispenser mechanism, unchanged, holds a Dispenser<Cup> or a Dispenser<Token>; only the report, which lives outside it, knows about plates. And snapshot hands back a copy rather than the live items array, so the report can reduce and filter over the remaining plates -- even sum their grams to 1900 -- without any risk of a stray push there corrupting the tube, which is the whole reason the method copies instead of returning the private field.

The program has real defects, and the sharpest hides in the serve count. served is incremented on rack.serve() !== undefined, which reads correctly only because a Plate is never undefined; the moment the tube is a Dispenser<number | undefined> and a genuine undefined is served, the count treats a real plate as an empty tube, because the sentinel the code uses to mean "nothing came out" is a value T is allowed to hold. Beyond that, the container is generic but the report is not: every line of it is wired to Plate's fields, so swapping T breaks run even though Dispenser is untouched, and the genericity stops dead at the class boundary. The by kind line filters out kinds with none present, so the served bowl simply vanishes from the summary with no way to tell "no bowls on the rack now" from "bowl is not a kind we stock"; and rejected: 1 is a bare tally that never names P6 as the plate that overflowed, so the report records that something was refused but not what.


Common Mistakes

  1. Typing serve() or pop() as T: an empty tube has nothing to give, so the honest return is T | undefined; claiming T is how a downstream .code throws on an empty container.
  2. Storing the contents as any[] inside the class: private items: any[] keeps the generic syntax while throwing away every guarantee it buys; the tube's label becomes a lie.
  3. Declaring a static field of the class type: static latest: T is refused with TS2302, because a static is shared across all instances and there is no single T for it to be.
  4. Writing item instanceof T: the class parameter is erased at run time, so it cannot be tested; sort by a discriminant field on the item or a validator passed in.
  5. Returning the live private array from a snapshot: return this.items lets a caller push straight into the tube; return [...this.items] so the outside cannot mutate the inside.
  6. Instantiating with any: new Dispenser<any>() compiles and then quietly widens every value that flows out of it, degrading inference everywhere downstream.
  7. Putting a parameter on the class when it varies per call: a map that changes the element type needs its own U on the method, not a second parameter bolted onto the class.
  8. Assuming implements Store<T> checks the private fields: an interface constrains only the public surface, so a mistyped private array is caught by its own annotation, not by the implements.
  9. Annotating what inference already knows: new Boxed<number>(5) restates what new Boxed(5) infers; the redundant argument is one more thing to get wrong when the value's type changes.

Best Practices

  • Return T | undefined or throw for the empty case: make the signature tell the truth about a tube that may have nothing to give, so the caller is forced to handle it.
  • Keep the backing store private and hand out copies: expose snapshot(): readonly T[] returning [...items], never the live array, so callers cannot reach past the doors.
  • Put the type parameter where the type actually varies: on the class for the instance's element type, on the method for a per-call transform like map<U>.
  • Program against the generic interface, not the concrete class: take a Store<T> so the implementation behind it stays swappable without touching a single caller.
  • Let construction infer the parameter: write new Boxed(5), not new Boxed<number>(5), and let the argument fix T.
  • Give a type parameter a default for the common case: interface Store<T = Tray> keeps the frequent instantiation short while the rare one still names its type.
  • Use a static factory with its own parameter instead of a static field: static of<U>(...) builds the class where a static x: T is forbidden.
  • Keep container classes small: a class that needs four type parameters is usually two classes wearing one coat; split it.

Practice Exercises

  1. The Queue: Build class Queue<T> with enqueue(item: T), dequeue(): T | undefined, and a size getter backed by an array, and exercise it with strings and then with objects, confirming the element type is enforced.
  2. The Contract: Define interface Store<T> with load, serve and height, implement it twice -- once array-backed, once capacity-bounded -- and write a drain<T>(s: Store<T>): T[] that works against both without change.
  3. The Static Wall: Add static latest: T to a generic class and read the TS2302 error, then replace it with a static of<U>(first: U) factory that returns an instance and explain why the method form is allowed.
  4. The Undefined Trap: Build a Dispenser<number | undefined>, serve a genuine undefined, and show that a serve() !== undefined counter miscounts it; then fix the count by comparing height before and after instead.