Arrays & Tuples: Ordered Shelves

Arrays & Tuples: Ordered Shelves in TypeScript: Behind the machine shop there is a small room kept at twenty degrees where the measuring kit lives, and it…

The Analogy: The Gauge Room at the Machine Shop

Behind the machine shop there is a small room kept at twenty degrees where the measuring kit lives, and it holds two completely different kinds of storage. Along the left wall runs a steel shelf of identical open bins holding ring gauges: forty this morning, thirty-eight next week, room for another forty if the shop buys them. On the bench sits a fitted case for the micrometer set: five recesses cut into black foam, each the exact silhouette of one instrument, laid out left to right in ascending range.

The shelf's rule is about count and kind, nothing else. Bin seventeen and bin thirty-one hold the same sort of object, and when a gauge comes back from a job the storeman drops it in whichever bin is free without relabelling anything. He has two questions at the door: how many are on the shelf, and is this thing a ring gauge. What he cannot tell you is anything about bin seventeen in particular, because position on that shelf is an accident of what came back first.

The case works the other way round: the recess is the label. The second hollow is the 25 to 50 millimetre body and the foam is cut so that instrument sits flush in it; the flat channel takes the setting standard and nothing else will lie in it. Nobody writes on the case, because a missing tool leaves a hole shaped like itself. The count never changes either: five recesses when the case was bought, five today, five when it is thrown out.

The failure mode is that the middle recesses are nearly the same size. The 25 to 50 body will drop into the 50 to 75 hollow, sit slightly loose, and the lid will still close over it. Nothing tears, nothing rattles, and the case looks complete on the bench. Then a fitter is told to check a 40 millimetre bore with the second micrometer, reads 40.02 off an instrument whose zero is twenty-five millimetres from where he thinks it is, and writes that figure on an inspection sheet that looks exactly like a correct one. The shelf has its own version: a job card says take the fourth ring gauge, only three came back that morning, and the card still wants a number, so the nominal size gets copied across. Both times the storage made a claim about itself that nobody checked.


Syntax or Core Structure

An array type answers two questions: what kind of thing is in it, and nothing about how many. A tuple type answers the opposite pair: exactly how many slots, and what belongs in each. Both compile down to the same runtime object -- a plain JavaScript array -- so every difference between them is a difference in what the compiler will let you write. Every line below compiles under strict:

// src/shelf.ts
// A shelf: any number of boxes, every box the same kind.
const gaugeMicrons: number[] = [1005, 1010, 1020, 1050];
const kinds: Array<string> = ["slip", "ring", "plug"];   // identical to string[]

// Parentheses matter: one shelf that accepts either kind of box.
const labels: (string | number)[] = ["ring", 50, "plug", 25];

// A tray: fixed positions, each with its own type and its own name.
type Reading = [gauge: string, nominalMicrons: number, passed: boolean];
const trial: Reading = ["ring-50", 50000, true];
const [gauge, nominalMicrons, passed] = trial;

// A tray with a shelf on the end: one pinned slot, then as many numbers as arrive.
type Certificate = [serial: string, ...deviations: number[]];
const cert: Certificate = ["G-4471", -2, 0, 3];
const [serial, ...deviations] = cert;

// readonly seals a shelf; an optional slot is the one index TypeScript is honest about.
const sealed: readonly number[] = [40, 60, 80];
const frozen = [40, 60] as const;          // readonly [40, 60]
type Span = [start: number, end?: number];
const openEnded: Span = [12];
const closed: Span = [12, 30];

console.log(gaugeMicrons.length, kinds.length, labels.length);
console.log(gauge, nominalMicrons, passed);
console.log(serial, deviations.length, deviations.join("/"));
console.log(sealed.length, frozen[0] + frozen[1]);
console.log(openEnded.length, closed.length, String(openEnded[1]));

Output:

4 3 4
ring-50 50000 true
G-4471 3 -2/0/3
3 100
1 2 undefined

Four things there are worth pinning down. Array<string> and string[] are the same type written two ways. Destructuring cert splits a tuple into its pinned head and its variable tail, which is why deviations is a number[] of three items. frozen[0] + frozen[1] is arithmetic on the literal types 40 and 60 and still produces a plain number. And the last line prints undefined because an optional tuple slot is typed as possibly missing -- which is exactly what ordinary array indexing is not.


Technical Depth: Position, Length, and What Survives to Runtime

Inference picks the shelf, never the tray

Write an array literal with no annotation and TypeScript gives you a shelf every time, because a shelf is what people usually mean. If you want the fitted tray you have to ask, and there are exactly three ways to ask: annotate the variable, write as const, or let a function's return type do the asking for you.

// src/infer.ts
const pair = [51, -12];                    // number[], not [number, number]
const fixed: [number, number] = [51, -12];
const frozen = [51, -12] as const;         // readonly [51, -12]

function span(): [start: number, end: number] {
    return [0, 10];                        // contextually typed by the return annotation
}

const [start, end] = span();
console.log(pair.length, fixed.length, frozen.length);
console.log(start, end, frozen[0] - frozen[1]);

Output:

2 2 2
0 10 63

All three variables print length 2, and only two of them have a length the compiler knows. Hover pair.length and you get number; on fixed or frozen you get the literal type 2. That difference is the whole subject of this lesson: pair is a claim about kind, fixed is a claim about shape. Note also that span needs no as const and no cast -- the annotated return type flows inward and types the literal [0, 10] as a tuple.

The shelf, the tray and the sealed tray, side by side

Take one expression at a time and ask what each of the three types allows. The error codes below are the ones tsc actually prints.

What you writenumber[][number, number]readonly [number, number]
const x: T = [1, 2]finefinefine
const x: T = [1]fineTS2322, source has 1 element and the target requires 2TS2322, same message
static type of x.lengthnumberthe literal 2the literal 2
x.push(3)finecompiles, and the length in the type becomes a lieTS2339, there is no push
x[5]number, under strict aloneTS2493, no element at index 5TS2493, no element at index 5
x.map((n) => n + 1)number[]number[], the length is droppednumber[]
Math.max(...x)finefinefine
assigning x into a number[]finefineTS4104, readonly into mutable

Two rows there are surprising. A tuple type does not stop push, and a tuple's map gives back a shelf rather than a tray of the same shape. The first is a genuine hole, shown running in the next section; the second is deliberate, since map is typed once for all arrays.

The hole: a tuple can be pushed into

A tuple type is an array type with extra promises bolted on, and it inherits every method Array has, including the ones that change the length. Nothing below is an error:

// src/tray.ts
type Pair = [number, number];
const tray: Pair = [40, 60];

tray.push(80);                  // accepted: push comes from Array and takes a number
console.log(tray.length, JSON.stringify(tray));

const [a, b] = tray;            // the type still says exactly two numbers
console.log(a + b, tray.slice(2).join(","));

const sealedTray: readonly [number, number] = [40, 60];
// sealedTray.push(80);         // this one is refused
console.log(sealedTray.length);

Output:

3 [40,60,80]
100 80
2

Read the first line again. The static type of tray.length is the literal 2, and the program printed 3. The destructuring on the next line quietly ignores the third reading, and slice(2) -- typed as number[] and therefore not subject to the tuple's length claim -- is the only expression in the file that can see it. Uncommenting the push on the sealed tray is what closes the door:

Output (tsc, not run):

error TS2339: Property 'push' does not exist on type 'readonly [number, number]'.

That is the practical rule: if a tuple's length is load-bearing, mark it readonly. That is not about protecting the caller's data here, it is about making the length in the type true.

Indexing is a promise, not a check

The shelf has three bins and the job card asks for the fourth. TypeScript's default answer is to believe the card:

// src/fourth.ts
const shelf: number[] = [1005, 1010, 1020];

const fourth = shelf[3];                     // static type: number. Runtime value: undefined.
console.log(String(fourth), typeof fourth);
console.log(String(shelf.at(-1)), String(shelf.at(-4)));

const found = shelf.find((mm) => mm > 2000);
console.log(String(found));

Output:

undefined undefined
1020 undefined
undefined

Three different reads, three undefined results, and only two of them were typed honestly. at and find are declared to return the element type or undefined, so the compiler makes you deal with the gap. Plain shelf[3] is declared to return the element type, full stop, which is why typeof fourth prints undefined while the editor insists the variable is a number. noUncheckedIndexedAccess changes that one rule:

// tsc --strict --noUncheckedIndexedAccess
const fifth = shelf[4];        // now typed as a number that might be missing
// const total = fifth + 1;    // refused
const total = (fifth ?? 0) + 1;
console.log(total);

Output (tsc, for the commented line):

error TS18048: 'fifth' is possibly 'undefined'.

The flag is narrower than people expect. It changes index reads and array destructuring; it does not touch for (const mm of shelf) or shelf.forEach, where the element type stays a plain number.

Every slot form, and what it does to the length

Slot formExampleLength the compiler believesNotes
required[number, number]exactly 2every position has to be supplied
optional[number, number?]1 or 2reading the optional slot yields a possibly-missing value, no flags needed
trailing rest[string, ...number[]]1 or morethe pinned slots keep their own types
leading rest[...string[], number]1 or morethe last slot is pinned and the front is a shelf
named[start: number, end: number]exactly 2labels show in hover text and are erased on output
readonlyreadonly [number, number]exactly 2no push, and it will not go into a number[]

Tuples arrive whether you ask for them or not

Plenty of everyday expressions hand you a tuple without the word appearing in your code:

ExpressionWhat you get backWhy it is a tuple
Object.entries(row)an array of key-and-value pairsthe key is a string and the value is not
iterating a Map<string, number>one key-and-value pair per stepsame reason
shelf.entries()one index-and-element pair per stepindex first, element second
useState(0) in Reactthe value, then the setterthe API is destructured by position
Promise.all on an array literal of promisesone slot per promise, types kept apartthe literal is inferred as a tuple
[1, 4, 2] as constreadonly [1, 4, 2]as const freezes length and values together
"a,b".split(",")string[], never a tuplethe count cannot be known from the type

That last row catches people daily. line.split(",") on a CSV row you are certain has three fields is still a shelf of unknown length, so destructuring it under noUncheckedIndexedAccess gives three possibly-missing strings.

What actually reaches the runtime

Nothing about a tuple survives compilation. The slot names, the length, the per-position types: all of it is deleted, and what ships is an array literal that Array.isArray cannot tell apart from a shelf. That is why JSON.parse(text) as [number, number] is a claim nobody checked: if the text held [40], the assertion still compiles, the length is 1, and the sum of the two slots is NaN. Data crossing a boundary needs a runtime length check.

Inside a single compilation, though, the length claim is enforced properly:

const short: [number, number] = [40];
const long: [number, number] = [40, 60, 80];

Output (tsc, not run):

error TS2322: Type '[number]' is not assignable to type '[number, number]'.
  Source has 1 element(s) but target requires 2.
error TS2322: Type '[number, number, number]' is not assignable to type '[number, number]'.
  Source has 3 element(s) but target allows only 2.

"Requires" and "allows only" are two complaints from the same check, and they are why a tuple earns its keep: a shelf would have accepted both literals without a word.


Real World Example: The Calibration Register in the Gauge Room

Every gauge in the room is checked against a setting standard on a schedule, and the readings go on a register that says which instruments are still fit for which class of work. Each run is a tuple: a serial, a nominal size, and however many readings the fitter took.

// src/calibrate.ts
// tsc --strict --noUncheckedIndexedAccess

// [serial, nominal size in microns, ...however many readings were taken]
type Run = readonly [serial: string, nominalMicrons: number, ...observed: number[]];
type Grade = readonly [name: string, limitMicrons: number];

const TOLERANCE: readonly Grade[] = [
    ["grade0", 3],
    ["grade1", 6],
    ["grade2", 12],
];

const ORDER: readonly string[] = ["grade0", "grade1", "grade2", "reject", "no data"];

const RUNS: readonly Run[] = [
    ["G-4471", 50000, 50002, 50001, 50003],
    ["G-4472", 25000, 24993, 24995, 24994],
    ["G-4473", 10000, 10011, 10009, 10014],
    ["G-4474", 75000, 75001, 75000, 75002],
    ["G-4475", 5000],
];

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);
}

// The deviation with the largest magnitude, sign kept. Ties go to the earlier reading.
function widest(deviations: readonly number[]): number {
    let best = deviations[0] ?? 0;
    for (const d of deviations) {
        if (Math.abs(d) > Math.abs(best)) {
            best = d;
        }
    }
    return best;
}

function gradeFor(deviation: number): string {
    for (const [name, limit] of TOLERANCE) {
        if (Math.abs(deviation) <= limit) {
            return name;
        }
    }
    return "reject";
}

function register(runs: readonly Run[]): string {
    const lines: string[] = [pad("SERIAL", 9) + pad("NOMINAL", 9) + pad("N", 4)
        + pad("MAXDEV", 8) + "GRADE"];
    const verdicts: string[] = [];
    let readings = 0;
    let worst = 0;
    let worstSerial = "none";

    for (const run of runs) {
        // Two pinned slots, then the shelf: one line of destructuring gets all three.
        const [serial, nominalMicrons, ...observed] = run;
        const deviations = observed.map((mm) => mm - nominalMicrons);
        readings = readings + deviations.length;

        if (deviations.length === 0) {
            verdicts.push("no data");
            lines.push(pad(serial, 9) + pad(String(nominalMicrons), 9) + pad("0", 4)
                + pad("n/a", 8) + "no data");
            continue;
        }

        const deviation = widest(deviations);
        const grade = gradeFor(deviation);
        verdicts.push(grade);
        if (Math.abs(deviation) > Math.abs(worst)) {
            worst = deviation;
            worstSerial = serial;
        }
        lines.push(pad(serial, 9) + pad(String(nominalMicrons), 9)
            + pad(String(deviations.length), 4) + pad(signed(deviation), 8) + grade);
    }

    const tally = ORDER
        .map((name) => [name, verdicts.filter((v) => v === name).length] as const)
        .filter(([, count]) => count > 0)
        .map(([name, count]) => name + " x" + String(count));

    lines.push("readings taken: " + String(readings));
    lines.push("widest deviation: " + signed(worst) + " micron on " + worstSerial);
    lines.push("grades: " + tally.join(", "));
    return lines.join("\n");
}

console.log(register(RUNS));

Output:

SERIAL   NOMINAL  N   MAXDEV  GRADE
G-4471   50000    3   +3      grade0
G-4472   25000    3   -7      grade2
G-4473   10000    3   +14     reject
G-4474   75000    3   +2      grade0
G-4475   5000     0   n/a     no data
readings taken: 12
widest deviation: +14 micron on G-4473
grades: grade0 x2, grade2 x1, reject x1, no data x1

The tuple is doing real work here. Run pins position zero to a serial and position one to a nominal size, then hands the rest of the row to a shelf of readings, so one line of destructuring produces a string, a number and a number[], each usable immediately. That is why mm - nominalMicrons compiles without a guard and pad(serial, 9) compiles without a cast. Type those rows as (string | number)[] instead and all three uses break at once: the subtraction is refused because the operands might be strings, pad is refused because the serial might be a number, and every field then needs a cast.

The output reads straight down. G-4471 came in at plus two, plus one and plus three microns, so the widest is +3, which sits exactly on grade0's limit and passes, because the comparison is inclusive. G-4472 was undersize on all three readings, so the widest is -7 and the minus sign survives onto the register; 7 is past grade1's 6 but inside grade2's 12. G-4473's +14 is outside every band and comes back as reject. G-4475 has no readings at all, which the Run type permits, so it prints n/a and no data. The footer adds 3 + 3 + 3 + 3 + 0 to get 12 readings, names +14 on G-4473 as the widest deviation of the day, and tallies the verdicts in a fixed order, omitting grade1 because nothing landed there.

Several mistakes in this file are compile errors rather than wrong figures. Swap the first two entries of any row and tsc reports both positions, because a tuple checks slots and not just element kinds. Add a fourth pinned slot to Run and every literal in RUNS becomes a length error. The ?? 0 in widest is there because noUncheckedIndexedAccess types deviations[0] as possibly missing, and the as const inside tally is load-bearing in reverse: without it the pair infers as an array of string | number, and count > 0 is refused because the comparison cannot be applied to something that might be a string.

The limits are real. First, ORDER restates the grade names that TOLERANCE already holds, so adding a grade3 band gives correct rows and a silently incomplete summary -- one list, two sources of truth, and the duplicate is the one nobody remembers to edit. Second, Run says only "a serial, a nominal, and any number of readings", which is exactly how G-4475 reached the register; writing the type as [serial: string, nominalMicrons: number, first: number, ...rest: number[]] would have refused that row where somebody typed it. Third, widest breaks ties by position, so a gauge reading -7 and +7 reports whichever came first, and its ?? 0 fallback is unreachable from register because of the length guard, so any other caller handing it an empty list gets a confident zero instead of a refusal. Fourth, pad never truncates and the fields are plain number, so a nine-character serial or a fractional reading pushes every later column right and destroys the alignment that makes the register readable at all.


Common Mistakes

  1. Writing string | number[] for a mixed shelf: that type means "a string, or an array of numbers". The shelf you meant is (string | number)[], and the wrong version type-checks until the first .length.
  2. Trusting arr[10]: with strict alone, indexing an array hands back the element type whatever the index is, so a read past the end is typed number and valued undefined. noUncheckedIndexedAccess is the only switch that changes it.
  3. Believing a tuple's length is enforced: push is inherited from Array, compiles on a mutable tuple, and leaves the type claiming two slots while the object holds three.
  4. Forgetting as const on a returned pair: return [value, setValue] from a function with no return annotation infers as an array of the union, so the caller's destructuring gives both bindings the same widened type.
  5. Adding readonly T[] to one parameter and stopping there: a readonly array will not go into a slot that wants T[], so the annotation has to travel down the call chain. One honest signature forces three more.
  6. Calling sort() with no comparator on numbers: the default comparator compares elements as strings, so [10, 9, 1].sort() gives [1, 10, 9].
  7. Forgetting that sort, reverse and splice change the array in place: they return the same array they were called on, so const sorted = xs.sort(cmp) leaves xs sorted too and every other holder of that reference sees the new order.
  8. Reading a property straight off find: it returns the element or undefined, a compile error under strict and a crash without it.
  9. Letting a tuple grow past three slots: [string, number, boolean, number, string] is a record whose field names live only in your head. Once the positions stop being obvious, an object with named keys is safer.

Best Practices

  • Default to a shelf. Reach for a tuple only when position is what gives a value its meaning, and stop at three slots.
  • Name the slots. [start: number, end: number] costs nothing at runtime and turns every hover and mismatch message into something a reader can act on.
  • Turn on noUncheckedIndexedAccess and keep indexing at the edges. Iterate with for...of where you can, and where you must index, handle the missing case on that line.
  • Take readonly T[] in any parameter you do not mutate. It is documentation the compiler enforces, and it makes an accidental in-place sort impossible.
  • Mark a tuple readonly whenever its length is load-bearing. That is the only thing that removes push and makes the length in the type true.
  • Copy before sorting, and always pass a comparator. Write [...xs].sort((a, b) => a - b) for numbers even when today's data comes out right without it.
  • Put the unit in the name. nominalMicrons and limitMicrons are the same number to the compiler, so a unit mismatch can only be caught by a human reading it.
  • Pin the first slot when "at least one" is a real rule. [first: T, ...rest: T[]] moves an empty-input check from runtime to compile time.

Practice Exercises

  1. The Fourth Bin: take src/fourth.ts, switch on noUncheckedIndexedAccess, and fix every error it reports without using ! anywhere. Then write down which of the original reads were honestly typed before the flag and which were not.
  2. The Sealed Tray: declare const tray: [number, number] = [40, 60], push a third number onto it, and print tray.length beside the length its type claims. Mark it readonly, read the error, and say which of those two lengths was the wrong one.
  3. At Least One Reading: retype Run so that a row with no readings will not compile, delete the no data branch from register, and drop G-4475 from RUNS. The four surviving rows and the readings taken line must print exactly as they do above; the grades line will change, and you should be able to say why before you run it.
  4. One List, Not Two: derive ORDER from TOLERANCE so the grade names are written once, keeping reject and no data at the end of the tally. The register must print byte for byte identical, which is the only evidence that you changed the structure and not the behaviour.