Interfaces: The Digital Contract

Interfaces: The Digital Contract in TypeScript: The coupling store at a fire station is a rack of brass fittings and, pinned on a board above the bench, a…

The Analogy: The Coupling Store at the Fire Station

The coupling store at a fire station is a rack of brass fittings and, pinned on a board above the bench, a single sheet for each pattern in use. The sheet for the 65 millimetre instantaneous pattern lists four things and nothing else: the bore, the span across the lugs, the seat diameter, and the depth of the gasket recess, each with a nominal figure and a tolerance beside it. A coupling either agrees with that sheet or it does not.

What the sheet never mentions is who made the fitting. There is no approved-supplier list on the board and no stamp anybody looks for. A brass coupling that came off a lorry from a firm nobody at the station has heard of will connect to the pump if its four dimensions land inside the tolerances, and a coupling from the oldest name in the trade will not connect if its lug span is three millimetres wide. The sheet describes a shape, and the shape is the whole of the requirement.

Two more habits of the board matter. The 65 sheet is written as "everything on the 45 sheet, plus the two dimensions below", so widening the 45 pattern silently widens the 65 pattern with it. And when the manufacturer sends a revision that adds a fifth dimension, the station does not throw the old sheet away -- the new page goes up beside it and the fitter reads both as one list.

The failure mode is the dimension nobody wrote down. A coupling can match all four figures on the sheet and still be cut with a gasket seat a millimetre shallower than the fittings the station has always used, because seat depth was added to the sheet in 1998 and this batch was made to the older drawing. It couples. The lugs snap over. It holds at the two bar you get from the yard tap, which is the only pressure anybody tests it at. Then it lets go at eight bar during a working fire, and the sheet is not wrong -- it was just never a complete description of what the station actually depended on.


Syntax or Core Structure

An interface is a named list of members a value must have. It says nothing about where the value came from, nothing about what else the value has, and nothing at all at runtime. Members can be required, optional, readonly, or methods, and any object with the right shape satisfies the interface without ever naming it:

// src/contract.ts
interface Hose {
    readonly tag: string;          // stencilled once, never reassigned
    lengthM: number;
    pattern: string;
    lastTestedBy?: string;         // a new hose has never been tested
    describe(): string;            // a method member
}

const reel: Hose = {
    tag: "H-12",
    lengthM: 23,
    pattern: "instantaneous-65",
    describe() {
        return this.tag + " " + String(this.lengthM) + "m " + this.pattern;
    },
};

// Nothing below mentions Hose. It satisfies Hose anyway, extra member and all.
const spare = {
    tag: "H-13",
    lengthM: 18,
    pattern: "instantaneous-65",
    lastTestedBy: "AW",
    coilNumber: 4,
    describe() { return "spare " + this.tag; },
};

function stencil(h: Hose): string {
    return h.describe() + (h.lastTestedBy === undefined ? " untested" : " by " + h.lastTestedBy);
}

reel.lengthM = 25;                 // lengthM is not readonly
// reel.tag = "H-99";              // this one is refused
console.log(stencil(reel));
console.log(stencil(spare));
console.log(reel.tag, reel.lengthM, spare.coilNumber, spare.lengthM + reel.lengthM);

Output:

H-12 25m instantaneous-65 untested
spare H-13 by AW
H-12 25 4 43

Four things are worth naming. spare was never annotated and never told about Hose, yet stencil(spare) compiles, because the only question asked at that call is whether the argument has the members Hose lists. coilNumber is a member Hose says nothing about, and passing the value through a parameter typed Hose neither removes it nor complains about it. lastTestedBy is optional, so reading it yields a value that might be missing and the undefined check is not optional. And readonly tag is a compile-time rule only: the commented assignment is an error, but nothing in the emitted JavaScript stops anybody writing to tag at runtime.


Technical Depth: A Shape, Not a Membership

Nobody signs anything

An interface is satisfied by shape, and there is exactly one place where TypeScript tightens that rule: a fresh object literal. A literal written directly at the point of assignment or as an argument gets an extra pass, called the excess property check, which rejects members the target does not declare. The same literal stored in a variable first sails through.

// src/fresh.ts
interface Coupling {
    pattern: string;
    boreMm: number;
}

const measured = { pattern: "instantaneous-65", boreMm: 65, batch: "B7" };
const fromVariable: Coupling = measured;   // fine: extra members are allowed

// const fromLiteral: Coupling = { pattern: "instantaneous-65", boreMm: 65, batch: "B7" };

console.log(fromVariable.pattern, fromVariable.boreMm, measured.batch);

Output:

instantaneous-65 65 B7

Output (tsc, for the commented line):

error TS2353: Object literal may only specify known properties, and 'batch' does not exist in type 'Coupling'.

That asymmetry is deliberate rather than accidental. A literal written on the spot is almost always a typo when it carries an unexpected member, while a variable that happens to have more members than the parameter needs is the everyday case that structural typing exists to allow.

interface or type: the differences that are real

Most of the argument between the two keywords is taste. These rows are the places where the choice actually changes what you can write.

Capabilityinterfacetype
declaring the same name twicethe members merge into one listTS2300, duplicate identifier
building on another typeextends Base, checked at the declarationBase & Extra, checked where it is used
naming a unionnot possiblethe main reason type exists
naming a primitive, tuple or function typenot possibleroutine
a class implements ityesyes, if it describes an object
mapped and conditional formsnot possiblethe only option
how it prints in an errorusually by nameoften expanded into its members

The merging row is the one that decides real cases. It is why the DOM and Node type definitions are interfaces: a library or your own code can add members to Window from a separate file. It is also why an interface is the wrong choice for a name you want to be closed, since a second declaration anywhere in the program will quietly widen it.

extends stacks the requirements, and conflicts are caught at the declaration

// src/stack.ts
interface Fitting {
    pattern: string;
    boreMm: number;
}
interface Lugged extends Fitting {
    lugs: number;
}
interface Instantaneous extends Lugged {
    seatDiaMm: number;
}

// interface Narrow extends Fitting { boreMm: string; }

const c: Instantaneous = { pattern: "instantaneous-65", boreMm: 65, lugs: 2, seatDiaMm: 78 };
console.log(Object.keys(c).length, c.lugs, c.seatDiaMm - c.boreMm);

Output:

4 2 13

Output (tsc, for the commented line):

error TS2430: Interface 'Narrow' incorrectly extends interface 'Fitting'.
  Types of property 'boreMm' are incompatible.
    Type 'string' is not assignable to type 'number'.

Notice that the conflict is caught where Narrow is declared, not where somebody tries to use it. Written as an intersection, Fitting & { boreMm: string } is a perfectly legal type whose boreMm is never, and the complaint only arrives at the first assignment. Catching it at the declaration is the one concrete advantage extends has.

Two declarations, one list

// src/merge.ts
interface Sheet {
    pattern: string;
}
interface Sheet {
    seatDiaMm: number;
}

const page: Sheet = { pattern: "instantaneous-65", seatDiaMm: 78 };
console.log(page.pattern, page.seatDiaMm);

Output:

instantaneous-65 78

Both members are now required, and no error was reported anywhere. Write the same pair as type Sheet = ... twice and you get error TS2300: Duplicate identifier 'Sheet'. instead. Merging is the mechanism behind every declare global block that adds a property to Window, and it is the reason an interface name is never closed.

Member forms, and what each one commits you to

Member formExampleWhat it commits you to
required propertyboreMm: number;must be present, always
optional propertylastTestedBy?: string;may be absent; reads are possibly undefined
readonly propertyreadonly tag: string;assignment refused, at compile time only
method shorthandcheck(c: Lugged): void;parameters compared bivariantly, even under strictFunctionTypes
function-typed propertycheck: (c: Lugged) => void;parameters compared contravariantly under strictFunctionTypes
call signature(c: Lugged): number;the value itself is callable
construct signaturenew (spec: Sheet): Sheet;the value is a constructor, used with new

The two rows that are not a style choice

Those middle two rows describe the same member written two ways, and they are checked by different rules. Under strictFunctionTypes, a standalone function type compares its parameters contravariantly, which is the sound direction: a handler that accepts less than it is given is refused. Method shorthand is exempt and stays bivariant, because the array and DOM type definitions would not type-check otherwise. That exemption is a known hole, and it is easy to fall into:

// src/variance.ts
interface Base {
    pattern: string;
}
interface Lugged extends Base {
    lugs: number;
}

interface NeedsBaseMethod {
    fit(c: Base): void;
}
interface NeedsBaseProperty {
    fit: (c: Base) => void;
}

const narrow = { fit: (c: Lugged) => { console.log(String(c.lugs)); } };

const asMethod: NeedsBaseMethod = narrow;      // accepted: shorthand is bivariant
// const asProperty: NeedsBaseProperty = narrow;

asMethod.fit({ pattern: "instantaneous-65" }); // no lugs anywhere in sight

Output:

undefined

Output (tsc, for the commented line, essential lines only):

error TS2322: Type '(c: Lugged) => void' is not assignable to type '(c: Base) => void'.
  Property 'lugs' is missing in type 'Base' but required in type 'Lugged'.

Both interfaces describe a member called fit that takes a Base. One accepts a function that will read lugs off a value that has no lugs, and prints undefined at runtime for it; the other refuses at compile time. The only difference is a pair of parentheses in the declaration. Writing callbacks as properties rather than methods is the single cheapest soundness win an interface offers.

What reaches the runtime

Nothing. An interface emits no code, implements on a class emits no code, and there is no instanceof for an interface because there is no object to compare against. JSON.parse(text) as Coupling is a claim nobody checked, exactly as it was for tuples, and the fix is the same: a function that reads the members one at a time and returns a boolean. The interface then describes what that function proved, instead of standing in for the proof.


Real World Example: The Coupling Register at the Fire Station

Every fitting that comes into the store is measured against the sheet for its pattern and the figures go on a register. The sheet is an interface, the fitting is an interface, the verdict is an interface, and the gauge that turns one into the other is an interface with a method on it.

// src/couplings.ts
interface Dimension {
    readonly name: string;
    readonly nominalMm: number;
    readonly tolMm: number;
}

interface Sheet {
    readonly pattern: string;
    readonly dims: readonly Dimension[];
}

interface Reading {
    readonly dim: string;
    readonly valueMm: number;
}

interface Coupling {
    readonly tag: string;
    readonly maker: string;
    readonly readings: readonly Reading[];
}

interface Verdict {
    readonly tag: string;
    readonly measured: number;
    readonly worst: string;
    readonly verdict: string;
    readonly absent: readonly string[];
}

interface Gauge {
    readonly pattern: string;
    check: (c: Coupling) => Verdict;
}

const PATTERN_65: Sheet = {
    pattern: "instantaneous-65",
    dims: [
        { name: "bore", nominalMm: 65, tolMm: 1 },
        { name: "lugSpan", nominalMm: 84, tolMm: 2 },
        { name: "seatDia", nominalMm: 78, tolMm: 1 },
    ],
};

const STOCK: readonly Coupling[] = [
    { tag: "C-101", maker: "Alder", readings: [
        { dim: "bore", valueMm: 65 },
        { dim: "lugSpan", valueMm: 85 },
        { dim: "seatDia", valueMm: 78 }] },
    { tag: "C-102", maker: "Bexley", readings: [
        { dim: "bore", valueMm: 66 },
        { dim: "lugSpan", valueMm: 84 },
        { dim: "seatDia", valueMm: 78 }] },
    { tag: "C-103", maker: "Corby", readings: [
        { dim: "bore", valueMm: 65 },
        { dim: "lugSpan", valueMm: 88 },
        { dim: "seatDia", valueMm: 77 }] },
    { tag: "C-104", maker: "Denby", readings: [
        { dim: "bore", valueMm: 64 },
        { dim: "lugSpan", valueMm: 83 },
        { dim: "seatDia", valueMm: 80 }] },
    { tag: "C-105", maker: "Ashby", readings: [
        { dim: "bore", valueMm: 65 },
        { dim: "lugSpan", valueMm: 84 }] },
];

const ORDER: readonly string[] = ["fits", "rejected", "incomplete"];

function pad(text: string, width: number): string {
    return text + " ".repeat(Math.max(0, width - text.length));
}

function signed(value: number): string {
    return value < 0 ? String(value) : "+" + String(value);
}

function gaugeFor(sheet: Sheet): Gauge {
    return {
        pattern: sheet.pattern,
        check: (c: Coupling): Verdict => {
            const absent: string[] = [];
            let worstName = sheet.dims[0]?.name ?? "none";
            let worstOff = 0;
            let outside = 0;
            let measured = 0;
            for (const dim of sheet.dims) {
                const hit = c.readings.find((r) => r.dim === dim.name);
                if (hit === undefined) {
                    absent.push(dim.name);
                    continue;
                }
                measured = measured + 1;
                const off = hit.valueMm - dim.nominalMm;
                if (Math.abs(off) > dim.tolMm) {
                    outside = outside + 1;
                }
                if (Math.abs(off) > Math.abs(worstOff)) {
                    worstOff = off;
                    worstName = dim.name;
                }
            }
            const verdict = absent.length > 0 ? "incomplete" : outside > 0 ? "rejected" : "fits";
            return { tag: c.tag, measured, worst: worstName + signed(worstOff), verdict, absent };
        },
    };
}

function register(sheet: Sheet, stock: readonly Coupling[]): string {
    const gauge = gaugeFor(sheet);
    const lines: string[] = ["pattern: " + gauge.pattern,
        pad("TAG", 7) + pad("MAKER", 9) + pad("DIMS", 6) + pad("WORST", 10) + "VERDICT"];
    const verdicts: string[] = [];
    const gaps: string[] = [];
    let taken = 0;

    for (const c of stock) {
        const v = gauge.check(c);
        verdicts.push(v.verdict);
        taken = taken + v.measured;
        for (const name of v.absent) {
            gaps.push(v.tag + " " + name);
        }
        lines.push(pad(v.tag, 7) + pad(c.maker, 9) + pad(String(v.measured), 6)
            + pad(v.worst, 10) + v.verdict);
    }

    const tally = ORDER
        .map((name) => name + " x" + String(verdicts.filter((v) => v === name).length))
        .filter((entry) => !entry.endsWith("x0"));

    lines.push("dimensions measured: " + String(taken) + " of "
        + String(stock.length * sheet.dims.length));
    lines.push("verdicts: " + tally.join(", "));
    lines.push("not measured: " + (gaps.length === 0 ? "none" : gaps.join(", ")));
    return lines.join("\n");
}

console.log(register(PATTERN_65, STOCK));

Output:

pattern: instantaneous-65
TAG    MAKER    DIMS  WORST     VERDICT
C-101  Alder    3     lugSpan+1 fits
C-102  Bexley   3     bore+1    fits
C-103  Corby    3     lugSpan+4 rejected
C-104  Denby    3     seatDia+2 rejected
C-105  Ashby    2     bore+0    incomplete
dimensions measured: 14 of 15
verdicts: fits x2, rejected x2, incomplete x1
not measured: C-105 seatDia

Seven interfaces carry this file and not one of them appears in the output. Gauge is the interesting one: gaugeFor returns an object literal that is checked against Gauge at the return, so a misspelled member is caught in the factory rather than at the call site, and check is written as a function-typed property rather than method shorthand, which means its parameter is compared contravariantly. Verdict is doing the work a bag of loose variables would otherwise do: every field it declares is read by register, and adding a field to it makes the compiler point at the one return that has to supply it.

The figures follow the sheet. C-101 is one millimetre wide across the lugs against a two millimetre tolerance, so it is the widest deviation on the fitting and still a pass. C-102 is a millimetre oversize on the bore, which is exactly the tolerance and therefore inside it, because the comparison is on Math.abs(off) > dim.tolMm. C-103 is four millimetres wide across the lugs and rejected. C-104 passes on bore and lug span but its seat diameter is two millimetres over a one millimetre tolerance, which is also why worst reads seatDia+2 rather than one of the two smaller deviations. C-105 was never measured across the seat, so it gets no verdict at all: two dimensions taken, fourteen readings across the five fittings against the fifteen the sheet asks for, and its name on the not measured line.

The type checking here is honest about shape and silent about content. Every Reading carries a dim that is a plain string, so { dim: "boreDia", valueMm: 65 } -- a name that is not on the sheet -- is a perfectly valid Reading that no dimension will ever match, and the fitting reports as incomplete with no hint as to why. Making dim a union of the three names would catch it at the literal, and that union is what the next lessons are about.

The limits are real. First, Coupling requires readings but cannot require that the readings cover the sheet, which is the entire reason the absent machinery and the incomplete verdict exist; the interface describes a shape, and completeness against another value is not a shape. Second, worst is a pre-formatted string, so the register can print it but nothing downstream can sort or total on it -- the number was thrown away at the moment it was made presentable. Third, worstOff starts at zero and the comparison is a strict >, so a fitting dead on nominal reports bore+0, which reads like a measurement of the bore rather than the absence of any deviation, and a fitting whose largest deviations tie reports whichever the sheet lists first. Fourth, gaugeFor reads sheet.dims[0] for that initial name and falls back to "none", a branch no caller in this file can reach, so an empty sheet would produce a register of five rows all claiming none+0 and fits.


Common Mistakes

  1. Expecting an interface to reject extra members: it only does so for a fresh object literal. A variable with more members than the interface declares is assignable, which is the whole point of structural typing and the reason a typo in a config object survives being passed through one variable.
  2. Reaching for instanceof on an interface: there is nothing at runtime to compare against, and x instanceof Coupling will not compile. Narrowing an unknown value to an interface needs a predicate function that reads the members.
  3. Casting parsed JSON to an interface: JSON.parse(text) as Coupling type-checks and proves nothing. The first missing member surfaces as undefined somewhere far from the parse.
  4. Declaring an interface twice by accident: the two declarations merge silently, so a name reused in another file adds required members to yours and the errors appear at every object literal you already wrote.
  5. Writing callbacks as method shorthand: fit(c: Base): void compares its parameter bivariantly even under strictFunctionTypes, so a handler that needs more than Base is accepted and reads undefined at runtime. Written as fit: (c: Base) => void the same mistake is a compile error.
  6. Treating readonly as protection: it is a compile-time rule with no runtime component. Object.freeze is the runtime tool, and the two are unrelated.
  7. Adding ? where a value is genuinely required: an optional member turns one honest check at the boundary into a possibly-missing read at every use site, and the checks multiply through the call chain.
  8. Extending an interface to override a member with a narrower type: only a compatible narrowing is allowed, and an incompatible one is TS2430 at the declaration. An intersection accepts the same conflict and hands you a member typed never instead.
  9. Assuming an interface constrains the values inside it: dim: string accepts any string at all. Interfaces constrain which members exist, not which values are sensible.

Best Practices

  • Write callbacks as function-typed properties. onDone: (r: Result) => void is checked soundly; onDone(r: Result): void is not. It costs two characters and closes a real hole.
  • Mark every member you do not intend to reassign readonly. It documents intent, it is free at runtime, and it turns a class of accidental mutation into a compile error.
  • Annotate the return type of any function that builds an object. The object literal is then checked at the return, so the error lands in the factory rather than at whichever call site happens to read the missing member first.
  • Give an interface to any value that crosses a module boundary, and a predicate to any value that crosses a process boundary. The interface says what you expect; only the predicate proves it.
  • Prefer extends over an intersection when building on another interface. Conflicts are caught at the declaration instead of producing a member typed never that fails much later.
  • Reserve ? for members that are genuinely absent sometimes. If the value is always there but sometimes not known yet, a union with null says so more precisely and forces one check instead of many.
  • Keep the numbers on your interfaces as numbers. Formatting inside the type is how a field becomes unsortable and untotalable one caller later.
  • Use interface for shapes that may be augmented and type for anything closed. Merging is a feature when you want an extension point and a hazard when you do not.

Practice Exercises

  1. The Dimension Nobody Wrote Down: add a fourth dimension to PATTERN_65 -- seatDepth, nominal 6 millimetres, tolerance 1 -- and run the register unchanged. Explain why every one of the five fittings changes verdict, and why the type checker had nothing to say about it.
  2. The Fresh Literal: pass an object literal with an extra member straight into gauge.check, then assign the same literal to a const first and pass that. Quote both results and say in one sentence which rule fired and which did not.
  3. Shorthand Versus Property: change Gauge.check from a function-typed property to method shorthand, then write a Gauge whose check takes a parameter narrower than Coupling. Show that it compiles as a method and is refused as a property, and say what the runtime consequence is.
  4. Keep the Number: change Verdict.worst into two members, a dimension name and a signed number, and have register do the formatting. The register must print byte for byte identical, and the new shape must let you add a line naming the single widest deviation across the whole of STOCK.