← 中文资源

简体中文版本

ReadonlyMap 类型守住公开 API 的只读边界

公开签名用 ReadonlyMap 与 readonly 数组接收数据:调用方拿不到 set 或 push 等写方法,内部 Map 仍可写,需要变更时显式复制,所有权边界写在类型上。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

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

实现说明

底层就是函数 quote、discountView。

使用要点

  • 跑完文件,输出里会留下标记——quote total cents:、visible rates:、owned copy length:。

常见问题

除了语言运行时还需要什么准备?

什么都不需要——语言运行时是唯一要求。 文件在加载时定义 quote、discountView。

主签名形如 function quote(lines: readonly CartLine[], rates: ReadonlyMap<string, number>)

核心语句

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],
]);

代码示例

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