typescript 28 lines · 6 steps

A type-safe groupBy in TypeScript

A generic helper that buckets items by any computed key, with the return type inferred from the key function.

Explained by highlit
1interface Order {
2 id: number;
3 customerId: string;
4 total: number;
5 status: 'pending' | 'shipped' | 'delivered';
6}
7 
8function groupBy<T, K extends PropertyKey>(
9 items: readonly T[],
10 keyFn: (item: T) => K,
11): Record<K, T[]> {
12 return items.reduce((groups, item) => {
13 const key = keyFn(item);
14 (groups[key] ??= []).push(item);
15 return groups;
16 }, {} as Record<K, T[]>);
17}
18 
19const ordersByStatus = groupBy(orders, (order) => order.status);
20const ordersByCustomer = groupBy(orders, (order) => order.customerId);
21 
22const revenueByCustomer = Object.entries(ordersByCustomer).map(
23 ([customerId, customerOrders]) => ({
24 customerId,
25 orderCount: customerOrders.length,
26 revenue: customerOrders.reduce((sum, o) => sum + o.total, 0),
27 }),
28);
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Generic type parameters let one function stay reusable while preserving precise types at every call site.
  2. 2reduce with a typed accumulator turns a flat list into a keyed structure in a single pass.
  3. 3Once data is grouped, Object.entries plus map is a clean route to per-key aggregates.

Related explainers

typescript
import { NestFactory } from '@nestjs/core';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { ValidationPipe } from '@nestjs/common';
import { ApiProperty } from '@nestjs/swagger';

Wiring validation and Swagger docs in NestJS

validation openapi decorators
Intermediate 8 steps
ruby
class TemplateInterpolator
  PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/
 
  def initialize(strict: false)

Interpolating templates with dotted keys in Ruby

regex string-interpolation hash-traversal
Intermediate 6 steps
typescript
import { Component, Input } from '@angular/core';
 
interface Order {
  id: string;

How Angular ICU plurals localize an order summary

i18n pluralization standalone-component
Intermediate 8 steps
typescript
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable, catchError, concatMap, finalize } from 'rxjs';
import { DataSource, QueryRunner } from 'typeorm';
 

Wrapping requests in a transaction with NestJS

interceptors transactions rxjs
Advanced 7 steps
typescript
type CsvColumn<T> = {
  header: string;
  value: (row: T) => string | number | boolean | null | undefined;
};

Building a type-safe CSV writer in TypeScript

generics serialization escaping
Intermediate 7 steps
typescript
import { parsePhoneNumberFromString, CountryCode } from 'libphonenumber-js';
 
export interface NormalizedPhone {
  e164: string;

Normalizing phone numbers to E.164 in TypeScript

validation normalization error-handling
Intermediate 7 steps

Share this explainer

Here's the card — post it anywhere.

A type-safe groupBy in TypeScript — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code