ReadonlyMap Types Keep Public APIs Read Only

Signatures that accept ReadonlyMap and readonly arrays expose views without mutation methods, so internal state stays writable while callers stay read-only.

TypescriptData Integrity

Code

typescriptsnippet
38 lines
// Public signatures take readonly collection types: callers get no write methods,
// the service keeps the full Map/array internally - the ownership boundary lives in the types
interface CartLine {
  sku: string;
  qty: number;
  unitCents: number;
}

const discounts = new Map<string, number>([
  ['pen', 0.9],
  ['notebook', 1],
]);

function quote(lines: readonly CartLine[], rates: ReadonlyMap<string, number>): number {
  return lines.reduce((sum, line) => sum + line.qty * line.unitCents * (rates.get(line.sku) ?? 1), 0);
}

// The returned view is read-only outside: set/delete do not exist on the type
function discountView(): ReadonlyMap<string, number> {
  return discounts;
}

const cart: readonly CartLine[] = [
  { sku: 'pen', qty: 2, unitCents: 250 },
  { sku: 'notebook', qty: 1, unitCents: 880 },
];

// cart.push(...) and discounts.set(...) are compile errors through these references
console.log('quote total cents:', quote(cart, discounts));
console.log(
  'visible rates:',
  [...discountView().entries()].map(([k, v]) => `${k}=${v}`).join(' '),
);

// Callers who need to mutate must copy explicitly - ownership stays clear
const owned = [...cart];
owned.push({ sku: 'eraser', qty: 3, unitCents: 120 });
console.log('owned copy length:', owned.length, 'cart still:', cart.length);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

quote total cents: 1330
visible rates: pen=0.9 notebook=1
owned copy length: 3 cart still: 2

What the code does

ReadonlyMap Types Keep Public APIs Read Only is built around the functions quote and discountView.

Applying it

The primary signature is function quote(lines: readonly CartLine[], rates: ReadonlyMap<string, number>)

Running the file prints labeled results such as quote total cents:, visible rates:, owned copy length: — each operation’s effect is visible in the output.

Statements that matter

return lines.reduce((sum, line) => sum + line.qty * line.unitCents * (rates.get(line.sku) ?? 1), 0);
const discounts = new Map<string, number>([
  ['pen', 0.9],
  ['notebook', 1],
]);

Interactive Tools for This Topic

FAQ

Any setup needed beyond the language runtime?
None — the language runtime is the only requirement. The file defines `quote`, `discountView` at load time.