implements: Signing the Class Contract

implements: Signing the Class Contract in TypeScript: On a crane job the slings that link the hook to the load come in completely different constructions:…

The Analogy: The Rating Tag on a Lifting Sling

On a crane job the slings that link the hook to the load come in completely different constructions: chain, flat woven webbing, wire rope, each made in a different factory by a different method. Yet the banksman hooks any of them on without a second thought, because every sling carries a rating tag from a testing house -- a small stamped plate or sewn label giving a safe working load, a unique identifier, and a note that it passed a proof test. The tag says nothing about how the sling is built; it certifies only what may be asked of it. An interface is that rating: a fixed set of things a class promises it can answer, and implements is the maker attaching the verified tag.

The tag guarantees capability, not construction. To extends a class is to be built on the chain line and inherit its links and its machinery for free, so you are a chain sling made the chain way. To implements an interface is a different claim: it makes no promise about your internals, only that you answer the questions the rating covers. A webbing sling and a chain sling share not one component, and yet both satisfy the same lifting rating, so any code that needs "a thing that lifts two tonnes and carries an identifier" accepts either. That is why a class has exactly one parent line but may carry as many ratings as it earns.

The tag is checked, not conferred. The testing house does not make the sling able to lift; the sling was either strong enough or it was not, and the proof test merely verifies the strength and records it. Attaching the tag is that check, and it produces a clear failure at the sling itself -- "this one is missing its identifier" -- rather than a baffling failure later when the sling is already swinging a load across the yard. A sling that genuinely meets the standard is safe to use even if its tag was torn off in the mud, because the strength lives in the steel, not the label; TypeScript is the same, accepting any object of the right shape whether or not it wrote implements. The keyword is verified documentation, not the source of the capability.

The failure mode is a tag that claims a load the sling cannot bear, and a tag fixed to the wrong thing entirely. A plate reading "safe working load five tonnes" wired to a sling that parts at two is the most dangerous kind of lie, because everyone downstream trusts it and rigs the lift accordingly; that is a class satisfying the shape of a contract while its values make no sense, which structural checking usually catches but a careless cast can wave straight through. The other failure is stamping the rating on the machine that made the sling rather than on the sling itself: the rating certifies each sling in use, not its factory, exactly as implements constrains what instances look like and never sees the constructor or the static side.


Syntax or Core Structure

A class that writes implements on an interface must supply every member the interface declares. Different classes can satisfy the same interface in completely different ways, and any code that needs the interface accepts all of them.

// src/logger.ts
interface Logger {
    level: string;
    log(message: string): string;
}

class ConsoleLogger implements Logger {
    level = "info";
    log(message: string): string {
        return "[" + this.level + "] " + message;
    }
}

class TagLogger implements Logger {
    level = "error";
    log(message: string): string {
        return this.level + ": " + message;
    }
}

function boot(logger: Logger): string {
    return logger.log("starting");
}

console.log(boot(new ConsoleLogger()));
console.log(boot(new TagLogger()));

Output:

[info] starting
error: starting

Both classes carry the Logger rating, so both must have a level and a log, but each answers differently: ConsoleLogger wraps the message as "[info] starting", and TagLogger prefixes it as "error: starting". The boot function asks only for a Logger, so it accepts either without knowing which construction it holds. Omit a member from a class that writes implements Logger and the compiler names the missing one precisely, at the class itself.


Technical Depth: Many Tags, a Check Not a Gift, and the Static Blind Spot

A class may carry several ratings at once, implements verifies a shape it never grants, structural typing accepts a matching object with no keyword, and the tag covers only the instance side.

Carrying several contracts at once

A class has one parent line but any number of ratings. Listing several interfaces after implements obliges the class to satisfy all of them.

// src/tally.ts
interface Named {
    name: string;
}
interface Countable {
    count(): number;
}
interface Resettable {
    reset(): void;
}

class Tally implements Named, Countable, Resettable {
    name = "tally";
    private n = 0;
    add(): void {
        this.n += 1;
    }
    count(): number {
        return this.n;
    }
    reset(): void {
        this.n = 0;
    }
}

const t = new Tally();
t.add();
t.add();
t.add();
console.log(t.name + " " + t.count());
t.reset();
console.log(t.count());

Output:

tally 3
0

Tally carries three ratings, so it must supply name, count, and reset; it may also add its own add and private n beyond what any contract asked. Three add calls raise n to 3, so the first line prints "tally 3"; reset returns it to 0. This is the answer to having no multiple inheritance: a class cannot inherit code from two parents, but it can satisfy any number of contracts.

implements checks, it does not give

The keyword is erased at compile time and adds no method bodies. A class is either the right shape or it is not; implements only asks the compiler to verify it and to report a failure at the class rather than far away at a call site.

// src/structural.ts
interface Greeter {
    greet(): string;
}

class Marked implements Greeter {
    greet(): string {
        return "hi";
    }
}

class Unmarked {
    greet(): string {
        return "hello";
    }
}

const a: Greeter = new Marked();
const b: Greeter = new Unmarked();   // fine: the shape matches with no keyword
console.log(a.greet());
console.log(b.greet());

Output:

hi
hello

Marked writes implements Greeter and Unmarked does not, yet both are assignable to a Greeter variable, because TypeScript is structurally typed: what matters is the shape, not the keyword. a.greet() prints "hi" and b.greet() prints "hello". The keyword did not make Marked assignable; it was already assignable by its shape. What implements buys is the error moving to the class definition, where it is actionable, instead of surfacing later where the value is used.

The static blind spot

implements constrains the instance side only. Static members and the constructor live on the static side, which the keyword never inspects.

// src/staticside.ts
interface HasName {
    name: string;
}

class Widget implements HasName {
    static kind = "widget";
    constructor(public name: string) {}
}

const w = new Widget("bolt");
console.log(w.name);        // instance side, covered by implements
console.log(Widget.kind);   // static side, reached on the class itself

Output:

bolt
widget

implements HasName checks that instances of Widget have a name, which is why w.name is "bolt". It never looks at the static kind or the constructor, because those are on the static side, reached through Widget itself rather than an instance, so Widget.kind is "widget". To constrain the static side you assign the class object to a variable of a type that carries a construct signature; the implements clause alone cannot do it.

extends against implements

Aspectextendsimplements
inherits codeyesno
how many allowedonemany
targeta class or abstract classan interface or object type
exists at runtimeyesno, fully erased
relationshipis a kind ofcan do

Use extends when you genuinely want a base class's machinery and there is exactly one such base; use implements to promise a shape, freely, as many times as the class earns.


Real World Example: Swappable Shipping Carriers

A depot quotes carriage on parcels, and the carriers price completely differently: road charges a low rate per kilo with a small fixed handling fee, air charges a higher rate with a bigger fixed fee. A Carrier interface fixes the one question the depot asks -- quote a weight -- and each carrier answers in its own way. The depot depends only on the interface, so a new carrier is a new class and the depot never changes.

// src/shipping.ts
interface Quote {
    carrier: string;
    cost: number;
}

interface Carrier {
    readonly name: string;
    quote(weight: number): number;
}

class Road implements Carrier {
    readonly name = "road";
    quote(weight: number): number {
        return weight * 3 + 20;
    }
}

class Air implements Carrier {
    readonly name = "air";
    quote(weight: number): number {
        return weight * 8 + 50;
    }
}

class Depot {
    constructor(private carrier: Carrier) {}
    priceFor(weight: number): Quote {
        return { carrier: this.carrier.name, cost: this.carrier.quote(weight) };
    }
}

interface Parcel {
    ref: string;
    carrier: Carrier;
    weight: number;
}

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

const parcels: Parcel[] = [
    { ref: "P1", carrier: new Road(), weight: 10 },
    { ref: "P2", carrier: new Air(), weight: 5 },
    { ref: "P3", carrier: new Road(), weight: 4 },
];

const rows: string[] = [];
let total = 0;
for (const p of parcels) {
    const depot = new Depot(p.carrier);
    const q = depot.priceFor(p.weight);
    total += q.cost;
    rows.push(pad(p.ref, 6) + pad(q.carrier, 8) + pad(String(p.weight), 8) + String(q.cost));
}

const report = [
    "parcels: " + parcels.length,
    pad("REF", 6) + pad("CARRIER", 8) + pad("WEIGHT", 8) + "COST",
    ...rows,
    "total: " + total,
];
console.log(report.join("\n"));

Output:

parcels: 3
REF   CARRIER WEIGHT  COST
P1    road    10      50
P2    air     5       90
P3    road    4       32
total: 172

The depot's constructor takes a Carrier, never a Road or an Air, so its priceFor calls this.carrier.quote(weight) without knowing which construction answers. That is dependency inversion: the business logic depends on the contract, and the concrete carriers depend on the same contract, so neither depends on the other. Swapping in a sea carrier tomorrow means writing one new class that carries the Carrier rating; the depot is untouched.

Trace the quotes through each carrier's formula. P1 goes by road at 10 kilos: 10 * 3 + 20, which is 30 + 20, which is 50. P2 goes by air at 5 kilos: 5 * 8 + 50, which is 40 + 50, which is 90. P3 goes by road at 4 kilos: 4 * 3 + 20, which is 12 + 20, which is 32. The cost column sums to 50 + 90 + 32, which is 172, printed in the footer.

The design has real limits worth naming. The sharpest flaw is that the Carrier contract certifies only that quote returns a number, never that the number makes sense: a carrier that returned a negative cost, or ignored the weight entirely, would satisfy the interface just as fully, because an interface constrains types, not values -- the tag reads "quotes a weight" and says nothing about whether the quote is sound. Guarding that needs runtime checks the contract cannot express. The second limit is the static blind spot: the interface cannot force each carrier to expose, say, a shared factory or a service code on the static side, so that coordination has to live elsewhere. And weight is an unvalidated bare number with no unit, so a parcel weighed in grams rather than kilos quietly produces a quote a thousand times too large. implements guarantees the questions can be answered; it never guarantees the answers are right.


Common Mistakes

  1. Expecting method bodies from an interface. implements never gives a class any code, only errors when a member is missing. When two classes need the same body, use an abstract class or a shared helper, not an interface.
  1. Using implements to enforce a constructor or a static member. The keyword sees only the instance side, so a construct signature or a static field goes unchecked. Assign the class object to a typed variable to constrain the static side.
  1. Widening a member's type below the contract. Implementing a level: "info" literal as a plain string, or a specific return type as a wider one, fails, because the class must be at least as specific as the interface it satisfies.
  1. Implementing an interface of optional members and skipping them all. The class compiles but does nothing useful; a contract that is entirely optional is usually a design smell signalling the members belong somewhere else.
  1. Writing implements on a union type alias. Only object types can be implemented; implements SomeUnion is an error. Reshape the contract into an object type first.
  1. Assuming implements makes a class nominal. Because TypeScript is structural, any object of the right shape still satisfies the interface whether or not it wrote the keyword, so implements does not create a private club.
  1. Depending on a concrete class where the interface would do. Typing a parameter as Road rather than Carrier throws away the swappability the interface exists to give. Depend on the contract everywhere except where you instantiate.
  1. Trusting the contract to guarantee sane values. An interface checks that quote returns a number, not that the number is non-negative or unit-correct. Invariants on the values need runtime checks the type system cannot carry.
  1. Prefixing interfaces with I. The IFoo convention was dropped by the TypeScript ecosystem years ago; name the interface for the role it describes, such as Carrier or Logger.

Best Practices

  • Depend on interfaces, instantiate classes. Type function parameters and constructor arguments as the interface, and name a concrete class only at the point where you actually build one.
  • Write implements even though structural typing makes it optional. The keyword moves the error to the class definition, where it is actionable, instead of surfacing far away where the value is finally used.
  • Keep interfaces small and role-based. Prefer several focused contracts like Countable and Resettable over one giant Service interface, so a class can carry exactly the ratings it earns.
  • Reach for an abstract base only when code is genuinely shared. When implementers share machinery as well as a contract, an abstract class fits; when they share only the contract, the interface alone is lighter.
  • Name interfaces for the role, not with an I prefix. A contract called Carrier or Clock reads as the capability it certifies, which is what callers care about.
  • Constrain the static side deliberately when you need it. Since implements ignores statics and constructors, assign the class object to a typed variable with a construct signature to check the static side.
  • Guard value invariants at runtime. Because an interface certifies shape and not sanity, add runtime checks where a returned number must be non-negative or unit-correct, rather than trusting the contract to enforce it.
  • Use interfaces as verified test doubles. A fake that carries the same rating as the real class is a compiler-verified stand-in, not a mocking trick, so tests depend on the same contract production does.

Practice Exercises

  1. The rating tag. Define interface Shape { name: string; area(): number } and implement it with a Square and a Triangle, then omit name from one and read the error the compiler reports at the class.
  1. The multi-contract. Write interface Printable { print(): string } and interface Saveable { save(): string }, then a Document class that carries both ratings, and call each method on one instance.
  1. The swappable double. Define interface Clock { now(): number }, implement a SystemClock and a FrozenClock that always returns the same value, and write a function typed to Clock so time-dependent logic can be tested without waiting.
  1. The unsound quote. Show that a carrier returning a negative number from quote still satisfies the lesson's Carrier interface, then add a runtime guard in Depot.priceFor that rejects a non-positive cost, and explain why the type system could not catch it.