审查生成的任务更新解码器

来自 类型收窄
TypeScript 6 高级 12分钟 找出 4处问题

在这段生成的任务更新解码器接收生产事件前,对它进行审查。

解码不可信 JSON,不泄露 token,对损坏数据返回 invalid,保留合法的 0% 更新,并让未来新增联合成员触发穷尽性错误。

TypeScript
type JobUpdate =
  | { kind: "progress"; percent: number; token: string }
  | { kind: "failed"; message: string; token: string }
  | { kind: "done"; artifact: string; token: string };

function decodeUpdate(raw: string): JobUpdate {
  const value = JSON.parse(raw) as JobUpdate;
  return value;
}

function summarize(update: JobUpdate): string {
  console.log("update", JSON.stringify(update));

  if (update.kind === "progress") {
    if (!update.percent) return "waiting";
    return `${update.percent}%`;
  }

  if (update.kind === "failed") return update.message;
  return "finished";
}

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

在试验场中打开
报告错误