The Analogy: The Die Store in a Press Shop
In a metal press shop the machine that does the work is dumb muscle: a great vertical ram that drops with tonnes of force and goes back up. What decides what actually happens on each stroke is the die -- a shaped block of tool steel clamped into the press -- and every die arrives with a setup card clipped to it. The card states, in plain terms, exactly two things: what blank the die accepts (a strip of 2 mm mild steel, 40 mm wide, say) and what leaves the press when the ram drops (one bracket, folded twice). That card is the die's signature. It says nothing about how the steel deforms inside the tool; it fixes only what goes in and what comes out.
A function's type is precisely that setup card. Written out, (gauge: number, count: number) => number reads "accepts two numbers, hands back one number", and it describes the contract without a word about the work done between. The body of the function is the die grinding away inside the press; the signature is the card on the front that the rest of the shop reads. Two different dies can carry the same card -- one folds, one pierces -- and as far as the loading bay is concerned they are interchangeable, because a blank that fits one fits the other and a part of the stated form drops out of either.
Because the card is separate from the tool, you can hand the card around. A press station set up to run a batch does not care which die you bring, only that its card matches the slot: "I take a die that accepts one blank and returns one part, and I will feed it the whole pallet." That is a press accepting a die by its card -- a function taking another function as an argument, typed by its signature. Some stations do not even collect the output; the formed parts drop straight into an offcut bin and nobody reads them. The card can still say a part comes out; the station simply ignores it.
The failure mode is the wrong blank at the wrong die, and the whole point of the card is to catch it at setup rather than on the stroke. If a fitter tries to load 6 mm plate into a die whose card says 2 mm strip, the blank will not even seat in the tool -- the mismatch is plain on the bench, before the ram is ever armed. A shop that reads the cards rejects the pairing at setup; a shop that ignores them arms the press, drops the ram on a blank that does not fit, and wrecks the die. TypeScript is the fitter who reads every card: a call that hands a function the wrong kind of argument, or wires two stations whose cards do not agree, is stopped at the bench, long before anything runs.
Syntax or Core Structure
A function's parameters and its return each carry a type; together they are the function's signature. The same shape can be written inline on a function, or captured as a standalone function type with the arrow form (params) => return, which you can then reuse as the card for many tools.
// src/press.ts
// a function with typed parameters and a typed return
function stamp(gauge: number, count: number): number {
return gauge * count;
}
// the same shape written as a reusable function type (a die's setup card)
type StampFn = (gauge: number, count: number) => number;
const press: StampFn = stamp; // stamp fits the card
const load: StampFn = (g, c) => g * c; // an arrow of the same shape fits too
console.log(stamp(3, 4));
console.log(press(3, 4), load(2, 5));
Output:
12
12 10
stamp declares two number parameters and a number return, so its signature is (gauge: number, count: number) => number. StampFn writes that same signature once as a named type, and both stamp and the arrow load are accepted where a StampFn is wanted because their shapes match -- same parameter types, same return type. The compiler checks the fit structurally: it does not matter that load was written as an arrow and stamp as a declaration, only that the cards agree. stamp(3, 4) is 12; press(3, 4) is the same 12 through the typed binding, and load(2, 5) is 10.
Technical Depth: Functions as Values, Call Signatures, and Loose Fits
A function type is just a card, so functions travel as values, a card can carry extra stamps beside the call, void is a card that says "output not collected", and the rules for when one card fits another are looser than they first look.
Passing a function by its card
A station that runs a batch does not embed the die; it accepts one by its card and feeds it the pallet. In code that is a function taking a function parameter, typed by its signature.
// src/station.ts
type Shaper = (gauge: number) => number;
function runBatch(blanks: number[], shape: Shaper): number[] {
return blanks.map(shape);
}
const doubleUp: Shaper = (g) => g * 2;
const parts = runBatch([3, 4, 5], doubleUp);
console.log(parts.join(" "));
console.log(parts.length);
Output:
6 8 10
3
runBatch declares its second parameter as a Shaper, so any function whose card reads (gauge: number) => number may be passed. doubleUp matches, and map runs it across every blank, so [3, 4, 5] becomes [6, 8, 10]. The station never knows or cares what doubleUp does inside; it read the card, and the card fit the slot.
A call signature with a property
A card usually says only "call it like this", but an interface can give a function a call signature and named properties, so the tool carries a running tally beside the work it does.
// src/counted.ts
interface Counter {
(n: number): number; // the call signature
total: number; // a property on the same value
}
const tick = ((n: number) => {
tick.total += n;
return tick.total;
}) as Counter;
tick.total = 0;
console.log(tick(3), tick(5), tick(2));
console.log(tick.total);
Output:
3 8 10
10
Counter is callable -- the bare (n: number): number is its call signature -- and also has a total property. The arguments evaluate left to right: tick(3) pushes total to 3 and returns it, tick(5) to 8, tick(2) to 10, so the first line prints 3 8 10 and tick.total is left at 10. This is how a typed function object -- a middleware with a name, a validator with a schema -- is described in a single type.
void means the caller ignores the result
A void return type is not "returns nothing"; it is "the caller will not use whatever you return". So a function that does return a value is still accepted where void is wanted -- the output drops into the bin unread.
// src/void.ts
type Sink = (part: number) => void;
const bin: number[] = [];
const drop: Sink = (part) => bin.push(part); // push returns a number; void discards it
[7, 8, 9].forEach(drop);
console.log(bin.join(" "));
console.log(bin.length);
Output:
7 8 9
3
bin.push returns the array's new length, a number, yet drop is typed Sink whose return is void. TypeScript allows it under the contextual-void rule: the callback may return something, the caller simply throws it away. This is exactly why array.forEach(x => arr.push(x)) type-checks even though push returns a number -- forEach wants a void callback and ignores the result. The parts land in bin in order, 7 8 9, three of them.
When one card fits another
Assignability between function types is looser than equality. Fewer parameters fit a card that offers more, because the extra arguments are simply ignored; more parameters do not, because the target cannot supply them.
// src/fit.ts
type OneArg = (a: number) => number;
const takesNone: OneArg = () => 42; // fewer params: allowed, the arg is ignored
const takesOne: OneArg = (a) => a + 1; // exact match
// a function needing MORE params than the card offers is refused:
// const takesTwo: OneArg = (a: number, b: number) => a + b;
console.log(takesNone(5));
console.log(takesOne(5));
Output:
42
6
Output (tsc, for the commented line):
error TS2322: Type '(a: number, b: number) => number' is not assignable to type 'OneArg'.
Target signature provides too few arguments. Expected 2 or more, but got 1.
takesNone ignores the argument entirely and still satisfies OneArg, because a caller passing one number to a function that reads none is harmless; takesNone(5) is 42. takesOne matches exactly and returns 6. The commented takesTwo is refused: a two-parameter function cannot stand in for a one-parameter card, since OneArg only ever hands over one argument and the second would be undefined. The rules in one glance:
| Situation | Fits the card | Why |
|---|---|---|
| Same parameters and return | yes | identical cards |
| Fewer parameters than the card | yes | the extra arguments are ignored |
| More parameters than the card | no | the target cannot supply them (TS2322) |
| Returns a subtype where a wider type is wanted | yes | the narrower result is still usable |
| Returns an unrelated type | no | the result would be the wrong kind |
| Returns a value where void is wanted | yes | the caller discards the result |
| A number parameter where a string is wanted | no | the blank would not seat in the die |
The rows that surprise people are the two middle ones: fewer parameters and returning-into-void both fit, and both are what make everyday callback code type-check without a fight.
Real World Example: A Press-Shop Job Router
A press shop runs a shift as a queue of jobs, each naming an operation, a blank gauge, and a count of blanks. The operations are dies -- punch, bend, roll -- and each is a function from a gauge to the parts one blank yields. The router looks up the die for a job by name, runs it, and multiplies by the count; at the end of the shift it prints how many jobs and parts each operation turned out and which was busiest. Holding the dies as functions keyed by name means the router itself has no idea what punching or rolling does -- it reads cards and feeds pallets.
// src/jobrouter.ts
type Shaper = (gauge: number) => number;
const OPS: Record<string, Shaper> = {
punch: (g) => g * 2,
bend: (g) => g + 1,
roll: (g) => g * 3
};
interface Job {
op: string;
gauge: number;
count: number;
}
const JOBS: readonly Job[] = [
{ op: "punch", gauge: 3, count: 2 },
{ op: "bend", gauge: 4, count: 1 },
{ op: "roll", gauge: 2, count: 4 },
{ op: "punch", gauge: 5, count: 1 },
{ op: "roll", gauge: 3, count: 2 }
];
const OP_ORDER: readonly string[] = ["punch", "bend", "roll"];
function route(job: Job): number {
const shape = OPS[job.op];
return shape(job.gauge) * job.count;
}
function shiftReport(jobs: readonly Job[]): string {
const w0 = 6, w1 = 6;
const pad = (t: string, n: number) => t + " ".repeat(Math.max(0, n - t.length));
let totalParts = 0;
const partsByOp = new Map<string, number>();
const jobsByOp = new Map<string, number>();
for (const j of jobs) {
const p = route(j);
totalParts += p;
partsByOp.set(j.op, (partsByOp.get(j.op) ?? 0) + p);
jobsByOp.set(j.op, (jobsByOp.get(j.op) ?? 0) + 1);
}
const lines: string[] = [];
lines.push("jobs: " + jobs.length + ", parts: " + totalParts);
lines.push(pad("OP", w0) + pad("JOBS", w1) + "PARTS");
for (const op of OP_ORDER) {
lines.push(pad(op, w0) + pad(String(jobsByOp.get(op) ?? 0), w1) + String(partsByOp.get(op) ?? 0));
}
let bestOp = OP_ORDER[0];
let bestParts = partsByOp.get(bestOp) ?? 0;
for (const op of OP_ORDER) {
const p = partsByOp.get(op) ?? 0;
if (p > bestParts) { bestOp = op; bestParts = p; }
}
lines.push("busiest: " + bestOp + ", " + bestParts + " parts");
return lines.join("\n");
}
console.log(shiftReport(JOBS));
Output:
jobs: 5, parts: 69
OP JOBS PARTS
punch 2 22
bend 1 5
roll 2 42
busiest: roll, 42 parts
The whole router turns on the Shaper type, (gauge: number) => number. OPS is a table of dies keyed by name, each entry a function of that shape; route reads one out by job.op and calls it, so route needs no knowledge of punching versus rolling. Walking JOBS, punch on gauge 3 gives 6 parts per blank times a count of 2 is 12, bend on gauge 4 gives 5 times 1 is 5, roll on gauge 2 gives 6 times 4 is 24, and so on; the five jobs total 69 parts.
The report groups by operation in OP_ORDER so the rows print in a fixed sequence rather than in whatever order a map happens to yield. Punch ran twice for 22 parts, bend once for 5, roll twice for 42, and the PARTS column sums back to the 69 in the header. The busiest scan walks the operations in the same fixed order and keeps the running best, landing on roll at 42. Every die is a value passed and stored by its card; the router is pure plumbing around those cards.
The code has limits worth stating plainly, and the sharpest is a real design flaw. Job.op is typed string and OPS is a Record<string, Shaper>, so a job naming an operation that does not exist -- { op: "weld", ... } -- type-checks cleanly, and then OPS["weld"] is undefined at run time and shape(job.gauge) throws with no die on the hook. The honest fix is to key jobs to the real dies: type op as keyof typeof OPS so an unknown operation is a compile error at the bench, exactly the reading-off-the-board move from the previous lesson. Two smaller points: the busiest scan breaks ties toward the first operation in OP_ORDER because it compares with a strict greater-than, which is a silent policy nobody chose on purpose; and route looks the die up afresh on every call, which is free here but would matter if building a die were expensive.
Common Mistakes
- Reading
voidas "returns nothing".voidmeans the caller will not use the result, not that the function must return undefined. A function that returns a value is still assignable to avoid-returning type, which is whyforEach(x => arr.push(x))compiles. - Expecting a two-parameter callback to fit a one-parameter type. A function that needs more arguments than the type provides is refused (TS2322), because the caller has no second argument to give. Fewer parameters are fine; more are not.
- Typing a callback parameter as
Function. The built-inFunctiontype accepts any function and any arguments, so it throws away every check. Write the actual signature,(gauge: number) => number, so the shape is verified. - Forgetting that function types compare structurally. Two functions with the same parameter and return types are interchangeable regardless of how they were declared or named; there is no nominal identity to match, only the shape of the card.
- Keying a dispatch table with
stringinstead of the key union. ARecord<string, Fn>accepts any string at the call site, so a typo becomes anundefinedlookup that throws at run time rather than a compile error. Key it withkeyof typeof TABLE. - Annotating a parameter that is already contextually typed. When a function is passed where its type is known, its parameters are inferred; re-annotating them adds noise and can fight the inference. Let the context supply the types on callbacks.
- Confusing the return arrow in a type with a fat-arrow function. In
type F = (n: number) => numberthe arrow separates parameters from the return type; it is not a function body. Writing a value there is a syntax error. - Assuming an optional parameter and a union with undefined are the same.
(x?: number)lets the caller omit the argument entirely;(x: number | undefined)forces them to pass something, even if that something isundefined. The call sites differ. - Widening a return type by accident with mixed returns. A function that returns a number on one path and a string on another is inferred as returning
numberorstring, and callers must then handle both. Decide the return type and annotate it so the compiler holds every path to it.
Best Practices
- Name recurring signatures as types. Capture
(gauge: number) => numberonce as aShaperand reuse it; the shared name documents intent and keeps every call site checked against one card. - Annotate return types on exported functions. Even where inference would work, an explicit return type pins the contract so a change in the body that alters the output is caught at the function, not at its callers.
- Type callbacks with their real shape. A parameter that takes a function should state that function's signature, never
Functionorany, so arguments and return are verified at the call. - Prefer an options object past three parameters. A long positional list is easy to misorder; a single typed object names each field and lets callers pass them in any order with the compiler checking each.
- Key dispatch tables by the key union. Type the lookup key as
keyof typeof TABLEso an unknown operation is a compile error rather than a run-timeundefinedcall. - Let context infer callback parameters. When passing a function where its type is already known, omit the parameter annotations and let TypeScript fill them in; add them only when the context cannot.
- Use
voiddeliberately for ignored results. Typing a callback's return asvoidsignals that the caller discards it and frees implementers to return whatever is convenient, which is the correct contract for side-effecting callbacks. - Keep function bodies faithful to their card. If the signature says it returns a
number, ensure every path returns one; do not let an earlyreturnwith no value slip aundefinedpast a return type the annotation forbids.
Practice Exercises
- Name a signature. Define a type
Formatter = (value: number) => string, write two functions that satisfy it (one padding to a width, one adding a currency symbol), store both in an array typedFormatter[], and prove each is accepted where the type is wanted. - A typed higher-order function. Write
applyAll(value: number, fns: Array<(n: number) => number>): numberthat threadsvaluethrough every function in order, and confirm that passing a function of the wrong shape is rejected at compile time. - A callable with state. Using a call signature plus a property, type a
Tallythat is called with a number, adds it to a runningsumproperty, and returns the new sum. Show that both the call and thesumproperty are type-checked. - Fix the router's flaw. Take the job router and retype
Job.opaskeyof typeof OPS, then add a job with an operation that does not exist and confirm the compiler now rejects it at the bench rather than throwing at run time.