Review generated entity index

from Generics
TypeScript 6 advanced 6 min 4 issues to find

Review this generated generic response index before it is used by a CLI.

Read an API array, validate that every item has a unique non-empty string id, index the items without reordering them, and print the count.

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

generated code is illustrative, not from any one model

Open in playground
Report an error