RecipesChapter 5: Conditional Types

Grouping Elements by Kind

Recipe 5.3 from The TypeScript Cookbook

function groupToys(toys: Toy[]): GroupedToys {
  const groups: GroupedToys = {};
  for (let toy of toys) {
    assign(groups, toy.kind, toy);
  }
  return groups;
}

function assign<T extends Record<string, K[]>, K>(
  groups: T,
  key: keyof T,
  value: K
) {
  // Initialize when not available
  groups[key] = groups[key] ?? [];
  groups[key]?.push(value);
}
Open in TypeScript Playground →