Generics
Advanced
Generics for Reusable Enterprise Code
Build reusable typed repositories, API clients, form helpers, and event utilities without losing domain safety.
46 min
3 sections
generics
constraints
repositories
sdk
1
2
3
01. Generic Functions Preserve Relationships
Section 1 of 3
Generics are useful when the input and output types are related. Do not add generic parameters just to look advanced. Use them when the function should preserve a caller-provided type.
typescript
function groupBy<T, K extends string | number>(
items: readonly T[],
getKey: (item: T) => K
): Record<K, T[]> {
return items.reduce((groups, item) => {
const key = getKey(item);
groups[key] = [...(groups[key] ?? []), item];
return groups;
}, {} as Record<K, T[]>);
}Exercise
Build a typed indexBy helper
Practice
Create a generic indexBy function that turns an array of objects into a lookup by a selected string key.
Back to Course