审查生成的转账边界

来自 品牌类型
TypeScript 6 高级 6分钟 找出 4处问题

在这个生成的转账边界处理不可信 JSON 前,对它进行审查。

解析正安全整数账户 ID 和分值,拒绝向自己转账,验证付款账户权限,并准确提交请求金额。

TypeScript
declare const brandKey: unique symbol;

type Brand<Value, Name extends string> = Value & {
  readonly [brandKey]: Name;
};

type AccountId = Brand<number, "AccountId">;
type Cents = Brand<number, "Cents">;

type Transfer = { from: AccountId; to: AccountId; cents: Cents };

declare function sendTransfer(from: AccountId, to: AccountId, cents: Cents): void;

function parseTransfer(raw: string): Transfer {
  const data = JSON.parse(raw) as Transfer;
  return data;
}

function submitTransfer(raw: string, currentAccount: AccountId): void {
  const transfer = parseTransfer(raw);
  if (transfer.from !== currentAccount) throw new Error("forbidden");

  const charged = transfer.cents + 25;
  sendTransfer(transfer.from, transfer.to, charged as Cents);
}

生成代码仅作示例,不代表任何特定模型

在试验场中打开
报告错误