Optional & Readonly: The Fine Print

Optional & Readonly: The Fine Print in TypeScript: When an object enters a museum it is written into the accession register, and the register makes three kinds…

The Analogy: The Museum Accession Register

When an object enters a museum it is written into the accession register, and the register makes three kinds of promise about every column. The accession number is stamped once at intake and never altered: it can be read, quoted on a label, copied into a catalogue, but the registrar who tries to change it is stopped, because the whole collection is cross-indexed on that number and altering it would orphan every reference. The current location, by contrast, is expected to change, and changes often, as the object moves between a gallery, the store and the conservation bench. Both columns are always present on the card; what differs is who may write to them after intake.

A third kind of column is the one that may simply be blank. The donor line is filled in for a bequest or a gift, and left empty for a purchase, because a purchase has no donor. The register has to cope with the card either way, and any clerk reading the donor line has to allow for its being empty before quoting it on a label. That is the difference between a column that must hold a value and a column that may or may not: the location is always something, the donor is sometimes nothing, and a clerk who forgets the second case will write a gallery label that reads as though it were fact.

The promises are also only as deep as the ink. Stamping the accession number does not physically weld the object to its number; it records an intention that the paperwork enforces on paper. If the object is a box, the register freezing the box's entry does not freeze what is inside the box: a conservator can still repack it, and the register will not notice, because the promise was made about the register line, not about the contents it points to. The locked display case is the thing that actually stops a hand; the register is only a rule.

The failure mode is the blank donor line read as a statement. A registrar in a hurry sees the empty column on a recent purchase, assumes it means "donor wished to remain anonymous", and prints "Anonymous gift" on the gallery caption. The blank never meant anonymous; it meant not-yet-recorded, and the object was in fact bought at auction. A column that is allowed to be empty carries two readings that look identical on the card, absent because there is nothing to record and absent because nobody has recorded it yet, and nothing in the register itself tells the two apart.


Syntax or Core Structure

The question mark after a property name makes it optional: the key may be absent, and its type gains undefined. The readonly modifier before a property name makes it write-once: it may be set when the object is built and never reassigned after. The two are independent, and a property may carry both.

// src/register.ts
interface Piece {
    readonly accession: string;    // stamped at intake, never reassigned
    readonly acquiredYear: number; // likewise fixed
    title: string;                 // required, and editable
    location: string;              // required, and editable
    donor?: string;                // optional: may be absent
}

const bequest: Piece = { accession: "1998.4.2", acquiredYear: 1998,
    title: "Astrolabe", location: "GAL-3", donor: "Aldous" };
const bought: Piece = { accession: "2004.1.1", acquiredYear: 2004,
    title: "Sextant", location: "STORE-B" };

bought.location = "GAL-3";         // allowed: location is not readonly
// bought.accession = "2004.1.2";  // refused: accession is readonly

console.log(bequest.accession, bequest.location, bequest.donor ?? "unknown");
console.log(bought.accession, bought.location, bought.donor ?? "unknown");
console.log(bequest.acquiredYear + bought.acquiredYear);

Output:

1998.4.2 GAL-3 Aldous
2004.1.1 GAL-3 unknown
4002

Output (tsc, for the commented line):

error TS2540: Cannot assign to 'accession' because it is a read-only property.

bought omits donor entirely and still satisfies Piece, because the question mark says the key may be absent. Reading it back gives undefined, which is why both reads guard with ?? "unknown" before printing. location is written to freely; accession refuses the write at compile time. The register line is enforced, not the ink: the next section shows how far that enforcement actually reaches.


Technical Depth: What the Fine Print Actually Promises

Both modifiers carry small print of their own. Optional means "or undefined", which changes how you read the value; the absent-versus-undefined distinction is subtler still; and readonly reaches exactly one level deep and not one step into the runtime.

Optional means "or undefined", so read it with ??

An optional property is not "sometimes there and always the right type"; it is the type with undefined added. You cannot use it until you have dealt with the undefined case, and the safe way to supply a default is ??, which fills in only for null and undefined, never for a legitimate 0 or empty string.

// src/schedule.ts
interface LoanOptions { retries?: number }

function schedule(opts: LoanOptions): number {
    // opts.retries.toFixed();   // refused: retries is possibly undefined
    return opts.retries ?? 3;    // default only when absent
}

console.log(schedule({}), schedule({ retries: 0 }), schedule({ retries: 5 }));

Output:

3 0 5

The middle call is the whole reason to prefer ?? over ||. A caller who deliberately passes zero retries means zero, and ?? keeps it, whereas opts.retries || 3 would treat the falsy 0 as missing and quietly substitute three. That single character is the difference between honouring a setting and overriding it.

Absent and present-but-undefined are two different cards

An optional key that is missing and a required key that holds undefined look almost the same, but they are distinct at the level of whether the key exists at all. One is a card with no donor line filled; the other is a card whose donor line has been struck through.

// src/present.ts
interface Loose { note?: string }               // the key may be absent
interface Strict { note: string | undefined }   // the key is required, may hold undefined

const p: Loose = {};                     // fine: note is simply absent
const q: Strict = { note: undefined };   // fine: note exists, holding undefined
// const r: Strict = {};                 // refused: note is required

console.log("note" in p, "note" in q);

Output:

false true

Output (tsc, for the commented line):

error TS2741: Property 'note' is missing in type '{}' but required in type 'Strict'.

The in operator reports the difference the type system was tracking: the key is genuinely not on p and genuinely on q. By default note?: string also accepts { note: undefined }, collapsing the two cases; if you need them kept apart, as on a PATCH payload where undefined means "clear this field" and absent means "leave it alone", the exactOptionalPropertyTypes flag stops an optional property from accepting an explicit undefined.

Readonly is one level deep, and gone at runtime

readonly freezes the binding, not what the binding points at. A readonly array property cannot be reassigned, but unless its element type is also readonly the array can still be pushed to; a readonly object property cannot be swapped, but its inner fields can still be written.

// src/shallow.ts
interface DisplayCase {
    readonly labels: string[];           // the binding is frozen, the array is not
    readonly plinth: { height: number };
}

const dc: DisplayCase = { labels: ["astrolabe"], plinth: { height: 90 } };
dc.labels.push("sextant");               // allowed: push mutates the array in place
dc.plinth.height = 120;                  // allowed: only plinth itself is frozen
// dc.labels = [];                       // refused: labels is a read-only property

console.log(dc.labels.join("/"), dc.plinth.height);

Output:

astrolabe/sextant 120

Both mutations land because readonly guards only the top level. To stop the array being pushed you write readonly labels: readonly string[], where the outer keyword blocks reassignment and the inner one blocks mutation; for a whole tree you need a recursive DeepReadonly mapped type. And none of this survives compilation: readonly is erased with the rest of the types, so the shipped JavaScript can reassign anything. The runtime equivalent, the locked case, is Object.freeze.

The two spellings that get confused, and the bulk switches

The modifier's position decides what it protects, and the standard library ships mapped types that flip these modifiers across a whole shape at once.

What you writeWhat it stops
readonly labels: string[]Reassigning labels; the array can still be pushed or sorted
labels: readonly string[]Mutating the array; labels itself can still be reassigned
readonly labels: readonly string[]Both: no reassignment and no mutation
Partial<T>Nothing; it makes every property optional
Required<T>Absence; it makes every property required
Readonly<T>Reassignment; it makes every property readonly
{ -readonly [K in keyof T]: T[K] }Nothing; it strips readonly back off

The first three rows are the same array typed three ways, and mixing up rows one and two is the single commonest readonly mistake. The last four are the bulk switches: Partial<T> for an update payload, Required<T> to assert a fully-populated record after validation, Readonly<T> to hand out a view nobody can edit, and the -readonly mapped form to reverse it.


Real World Example: The Accession Register

The register stores pieces, applies a batch of edits, and prints a sheet. The stored shape marks accession and acquiredYear readonly, so no edit can touch them, and derives the editable subset with Omit so the patch type cannot even name them. donor and valuation are optional, which is what makes the absent-versus-recorded distinction show up in the footer.

// src/collection.ts
type Location = "GAL-1" | "GAL-2" | "GAL-3" | "STORE-B" | "CONSERV";

type Piece = {
    readonly accession: string;
    readonly acquiredYear: number;
    title: string;
    location: Location;
    donor?: string;
    valuation?: number;
};

type Editable = Omit<Piece, "accession" | "acquiredYear">;
type Patch = Partial<Editable>;
type Edit = { accession: string; patch: Patch };

const PIECES: readonly Piece[] = [
    { accession: "1998.4.2", acquiredYear: 1998, title: "Astrolabe", location: "GAL-3",
        donor: "Aldous", valuation: 1200 },
    { accession: "2004.1.1", acquiredYear: 2004, title: "Sextant", location: "STORE-B" },
    { accession: "2011.7.9", acquiredYear: 2011, title: "Quadrant", location: "GAL-3",
        donor: "Verey", valuation: 450 },
    { accession: "1975.2.4", acquiredYear: 1975, title: "Compass", location: "STORE-B",
        donor: "Founding", valuation: 300 },
    { accession: "2019.9.5", acquiredYear: 2019, title: "Spoon", location: "CONSERV" }
];

const EDITS: readonly Edit[] = [
    { accession: "2004.1.1", patch: { location: "GAL-1" } },
    { accession: "2011.7.9", patch: { valuation: 500 } },
    { accession: "2019.9.5", patch: { location: "GAL-1", donor: "Vane", valuation: 60 } },
    { accession: "2099.9.9", patch: { location: "GAL-2" } }
];

const LOC_ORDER: readonly Location[] = ["GAL-1", "GAL-2", "GAL-3", "STORE-B", "CONSERV"];

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

function applyPatch(piece: Piece, patch: Patch): Piece {
    return { ...piece, ...patch };
}

function register(pieces: readonly Piece[], edits: readonly Edit[]): string {
    const current = new Map<string, Piece>(pieces.map((p) => [p.accession, p]));
    let applied = 0;
    for (const edit of edits) {
        const found = current.get(edit.accession);
        if (found === undefined) { continue; }
        current.set(edit.accession, applyPatch(found, edit.patch));
        applied += 1;
    }
    const rows = pieces.map((p) => current.get(p.accession) ?? p);

    const out: string[] = [];
    out.push("pieces: " + String(rows.length) + ", edits applied: "
        + String(applied) + " of " + String(edits.length));
    out.push(pad("ACC", 10) + pad("TITLE", 11) + pad("WHERE", 9) + pad("DONOR", 10) + "VALUE");
    for (const piece of rows) {
        out.push(pad(piece.accession, 10) + pad(piece.title, 11) + pad(piece.location, 9)
            + pad(piece.donor ?? "-", 10)
            + (piece.valuation === undefined ? "n/a" : String(piece.valuation)));
    }
    const priced = rows.filter((p) => p.valuation !== undefined);
    const totalVal = priced.reduce((sum, p) => sum + (p.valuation ?? 0), 0);
    const byLoc = LOC_ORDER
        .map((l) => [l, rows.filter((p) => p.location === l).length] as const)
        .filter(([, n]) => n > 0)
        .map(([l, n]) => l + " x" + String(n));
    const missing = rows.filter((p) => p.donor === undefined).map((p) => p.accession);
    out.push("total valuation: " + String(totalVal) + " GBP ("
        + String(priced.length) + " of " + String(rows.length) + " priced)");
    out.push("by location: " + byLoc.join(", "));
    out.push("donor not recorded: " + missing.join(", "));
    return out.join("\n");
}

console.log(register(PIECES, EDITS));

Output:

pieces: 5, edits applied: 3 of 4
ACC       TITLE      WHERE    DONOR     VALUE
1998.4.2  Astrolabe  GAL-3    Aldous    1200
2004.1.1  Sextant    GAL-1    -         n/a
2011.7.9  Quadrant   GAL-3    Verey     500
1975.2.4  Compass    STORE-B  Founding  300
2019.9.5  Spoon      GAL-1    Vane      60
total valuation: 2060 GBP (4 of 5 priced)
by location: GAL-1 x2, GAL-3 x2, STORE-B x1
donor not recorded: 2004.1.1

Read the sheet against the fine print. The two readonly fields never appear in Patch, because Editable omitted them before Partial was applied, so a route handler literally cannot write an edit that touches accession or acquiredYear; the guarantee is structural, not a runtime check. The two optional fields drive the footer: donor being absent on the sextant is what puts it in "donor not recorded", and valuation being absent is what makes the total say "4 of 5 priced" rather than pretending the collection is worth exactly 2060. The edits applied count is 3 of 4 because the fourth names an accession no piece holds.

The program has real defects worth naming, and they cluster around the optional fields. Because Patch is built with plain Partial, an omitted key means "leave alone" and there is no way to express "clear this donor": a patch can add a donor or change one, never remove one, so the register can accrete facts but not retract them. The unknown edit is dropped in silence; the sheet reports "3 of 4" but never says which one failed or why, so a registrar who fat-fingers an accession gets no signal beyond a count that is one short. The total valuation prints a bare "2060 GBP", and although the "4 of 5 priced" note is honest, a reader skimming the figure alone will take it for the whole collection's worth when a fifth of the pieces carry no price at all. And Location includes "GAL-2" solely so the skipped patch typechecks, a value that never reaches any row: a member of the union kept alive only by the dead edit that references it.


Common Mistakes

  1. Using the logical-or for defaults on optional numbers or booleans: opts.count || 10 turns a deliberate 0 into 10, and flag || true erases a deliberate false. Use ??, which fills in only for null and undefined.
  2. Marking too many fields optional: an interface where every property carries a question mark accepts the empty object and pushes all the real checking into runtime, where the type system can no longer help.
  3. Believing readonly protects data at runtime: it is erased at compile time and the shipped JavaScript can reassign anything; use Object.freeze or an immutable structure if you need real enforcement.
  4. Assuming readonly is deep: readonly plinth: { height: number } stops you swapping the object but not writing plinth.height, and a readonly array can still be pushed unless its elements are readonly too.
  5. Confusing readonly x: string[] with x: readonly string[]: the first blocks reassigning x, the second blocks mutating the array; write both to block both.
  6. Treating an absent optional and an explicit undefined as always identical: by default they are interchangeable, but on a PATCH payload the difference between "leave alone" and "clear" is real, and only exactOptionalPropertyTypes keeps them apart.
  7. Reading an optional property without handling undefined: opts.retries.toFixed() is refused because the value may be undefined; narrow or default it first.
  8. Hand-writing create, update and stored shapes as three separate interfaces: they drift apart the moment one changes; derive them from one entity with Omit, Pick and Partial.
  9. Using Partial<T> for a payload that must be able to clear fields: Partial can only omit or set, so a field cleared to undefined needs an explicit field?: T | null design instead.

Best Practices

  • Make identifiers and creation timestamps readonly on every entity type: it is one keyword per field and it removes a whole class of "who overwrote the id" bug at compile time.
  • Prefer readonly T[] for parameters you only read: it documents that the function will not sort or splice in place, and the compiler holds you to it.
  • Derive request and response shapes from one source-of-truth entity: Omit, Pick, Partial and Required keep the derived shapes in lockstep with the original as it changes.
  • Default optional values with ??, at the point of use, not by mutating the input: it keeps a legitimate zero or empty string and leaves the caller's object untouched.
  • Reach for the bulk mapped types deliberately: Partial<T> for an update payload, Required<T> to assert a validated record, Readonly<T> to hand out an uneditable view.
  • Turn on exactOptionalPropertyTypes on new projects: it keeps "missing" and "present but undefined" distinguishable, which matters the moment you build a PATCH endpoint.
  • When you truly need immutability, enforce it at runtime as well: pair the readonly type with Object.freeze or an immutable library, because the type alone ships as nothing.
  • Say what a cleared field means before choosing the type: if a field can be actively removed, model it as field?: T | null and treat null as the clear signal, rather than hoping undefined will carry two meanings.

Practice Exercises

  1. The Fine Print: Define Booking with a readonly reference, a required guestName, and an optional notes. Build a valid booking, try to reassign the reference, and read the TS2540 error.
  2. The Frozen Array: Write function total(prices: readonly number[]): number returning the sum, then add prices.sort() inside it, read the error, and explain in one sentence why a readonly array has no sort.
  3. The Two Blanks: Declare Loose { note?: string } and Strict { note: string | undefined }, build the empty object against each, and explain which one is refused and why "note" in reports differently.
  4. The Clear Patch: Take the collection.ts register, change Patch so a donor can be actively cleared as well as set, update applyPatch to honour a clear, add one edit that clears the Astrolabe's donor, and hand-trace the new "donor not recorded" line.