审查生成的实体索引

来自 泛型
TypeScript 6 高级 6分钟 找出 4处问题

在命令行工具使用这段生成的通用响应索引前,对它进行审查。

读取 API 数组,验证每项都有唯一且非空的字符串 id,在不重新排序的情况下建立索引,并输出数量。

TypeScript
type HasId = {
  id: string;
};

function indexResponse<T extends HasId>(raw: string): Map<string, T> {
  const parsed = JSON.parse(raw) as T[];
  parsed.sort((left, right) => left.id.localeCompare(right.id));

  const byId = new Map<string, T>();
  for (const item of parsed) {
    byId.set(item.id, item);
  }
  return byId;
}

type Account = HasId & { active: boolean };

const raw = process.argv[2]!;
console.log(indexResponse<Account>(raw).size);

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

在试验场中打开
报告错误