01
Write a generic TypeScript function that groups an array of items by a key.
Show answer
Generics keep the result strongly typed.
function groupBy<T, K extends keyof T>(items: T[], key: K): Record<string, T[]> {
return items.reduce((acc, item) => {
const group = String(item[key]);
(acc[group] ||= []).push(item);
return acc;
}, {} as Record<string, T[]>);
}
interface Order { id: number; status: string }
const byStatus = groupBy<Order, 'status'>(orders, 'status');
K extends keyof T ensures only real property names are accepted.