Review a generated transfer boundary

from Branded types
TypeScript 6 advanced 6 min 4 issues to find

Review this generated transfer boundary before it handles untrusted JSON.

Parse positive safe-integer account IDs and cents, reject self-transfers, authorize the source account, and submit exactly the requested amount.

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

generated code is illustrative, not from any one model

Open in playground
Report an error