TypeScript reduce: Typing Accumulators
The runtime behaviour of reduce takes about ten seconds to explain: walk the array, carry a value
along, return it at the end. Nobody gets stuck there. What people get stuck on is TypeScript reduce
errors — the accumulator that comes back as {}, the never[] that refuses every push, and the
red squiggle that appears on the line you were sure was correct.
All of that comes from one rule: the accumulator type is inferred from the initial value, and from nothing else. Once that clicks, the rest is mechanical.
The easy case, and why it is easy
Start with the version that just works.
const prices = [19, 29, 9]
const cartTotal = prices.reduce((sum, price) => sum + price, 0)
// cartTotal: numberThe initial value is 0, so the accumulator is number. The array is number[], so price is
number. The callback returns number, which matches the accumulator, and everyone is happy.
This case works because the initial value and the element type are the same. The moment they differ
— the moment you fold an array into an object, a Map, or a different shape of array — the
inference you were relying on stops helping you.
The overload that throws at runtime
reduce has three overloads in lib.es5.d.ts. Simplified, they look like this:
interface ReduceSignatures<T> {
// 1. No initial value: accumulator is the element type
reduce(cb: (acc: T, cur: T, index: number, arr: T[]) => T): T
// 2. Initial value of the element type
reduce(cb: (acc: T, cur: T, index: number, arr: T[]) => T, initial: T): T
// 3. Initial value of some other type U
reduce<U>(cb: (acc: U, cur: T, index: number, arr: T[]) => U, initial: U): U
}Overload 1 is the dangerous one. Drop the initial value and TypeScript tells you the result is
number, which is a lie:
const emptyPrices: number[] = []
const brokenTotal = emptyPrices.reduce((sum, price) => sum + price)
// ✅ Type-checks as number
// ❌ Throws at runtime: TypeError: Reduce of empty array with no initial valueThe type system has no idea whether an array is empty, so it cannot warn you. Always pass an initial value. It costs two characters and removes an entire class of production incident.
The {} trap
Here is the one everybody hits. You want to index an array of records by a key.
type Visitor = { id: string; country: string }
const visitors: Visitor[] = [
{ id: 'a1', country: 'DE' },
{ id: 'b2', country: 'US' },
{ id: 'c3', country: 'DE' },
]
const byCountryBroken = visitors.reduce((group, visitor) => {
// group[visitor.country] = visitor
// ❌ Element implicitly has an 'any' type because expression of type 'string'
// can't be used to index type '{}'. (7053)
return group
}, {})The initial value is {}, so U is inferred as {} — the type with no known properties. Assigning
to an arbitrary string key on it is an error, and so is reading one back.
The empty array version fails the same way for the same reason:
const germanIdsBroken = visitors.reduce((ids, visitor) => {
// if (visitor.country === 'DE') ids.push(visitor.id)
// ❌ Argument of type 'string' is not assignable to parameter of type 'never'. (2345)
return ids
}, [])[] is inferred as never[], and never accepts nothing. The error names a type you never wrote,
which is why this one burns so much time.
Fix one: annotate the initial value
Inference follows the initial value, so give the initial value a type.
const byCountryAnnotated = visitors.reduce(
(group, visitor) => {
group[visitor.country] = visitor
return group
},
{} as Record<string, Visitor>,
)
// byCountryAnnotated: Record<string, Visitor>as is doing real work here and it is not free: you are promising that the object will eventually
have those keys while it is still empty. That promise is fine for an accumulator you are about to
fill, and it is exactly the promise the next section makes you pay for.
The array case reads better, because a plain annotation does the job without an assertion:
const germanIds = visitors.reduce((ids: string[], visitor) => {
if (visitor.country === 'DE') ids.push(visitor.id)
return ids
}, [])
// germanIds: string[]Fix two: pass the type argument
Overload 3 is generic, so you can supply U directly instead of annotating anything:
const byCountryGeneric = visitors.reduce<Record<string, Visitor[]>>(
(group, visitor) => {
const bucket = group[visitor.country] ?? []
bucket.push(visitor)
group[visitor.country] = bucket
return group
},
{},
)
// byCountryGeneric: Record<string, Visitor[]>This is the version to reach for. The type sits next to the method name where a reader looks first,
the {} literal is checked against Record<string, Visitor[]> instead of being inferred from it,
and there is no as lying about the current contents. If you only remember one thing about typing
reduce, remember reduce<U>(...).
See TypeScript Record for why Record<string, V> is the right
accumulator shape here and what it costs you.
Your group-by result is lying to you
Record<string, Visitor[]> says every string key maps to an array. It does not:
const unknownBucket = byCountryGeneric['FR'] // Visitor[] — but it is undefined
// unknownBucket.length
// 💥 TypeError: Cannot read properties of undefined (reading 'length')That is not a reduce bug, it is how index signatures work everywhere in TypeScript. The fix is the
noUncheckedIndexedAccess compiler flag, which turns every index read into Visitor[] | undefined
and forces you to handle the miss. It is the single highest-value strict-adjacent flag for code
that does a lot of grouping, and the ?? [] in the example above is the pattern it pushes you
toward.
If you only need counts, Record<string, number> with a ?? 0 default behaves the same way and is
worth the same caution.
Narrowing inside the callback
A discriminated union accumulator works, and narrowing behaves normally inside the callback body:
type AppEvent =
| { kind: 'click'; target: string }
| { kind: 'purchase'; cents: number }
const appEvents: AppEvent[] = [
{ kind: 'click', target: 'buy' },
{ kind: 'purchase', cents: 2900 },
{ kind: 'click', target: 'docs' },
]
const eventTotals = appEvents.reduce<{ clicks: number; revenue: number }>(
(totals, appEvent) => {
if (appEvent.kind === 'purchase') {
// appEvent is narrowed to the purchase member here
return { ...totals, revenue: totals.revenue + appEvent.cents }
}
return { ...totals, clicks: totals.clicks + 1 }
},
{ clicks: 0, revenue: 0 },
)Two things to notice. Returning a fresh object every iteration keeps the callback pure, which reads
well but allocates once per element — fine for hundreds of items, measurable for hundreds of
thousands. And the narrowing works on the element, never on the accumulator: TypeScript cannot
track what totals became on the previous pass, so an accumulator whose type changes as the fold
progresses is not something reduce can express.
Discriminated unions are worth reading if the kind
field above is new to you.
Reduce over an object
The standard object-to-object transform pairs reduce with Object.entries:
const rawSettings = { theme: 'dark', locale: 'en', density: 'compact' }
const upperSettings = Object.entries(rawSettings).reduce<Record<string, string>>(
(settings, [settingKey, settingValue]) => {
settings[settingKey] = settingValue.toUpperCase()
return settings
},
{},
)The tuple destructuring in the parameter list is what makes this readable. Be aware that
Object.entries widens keys to string even when the input has literal keys, so the result loses
the original key union — Object.entries in TypeScript covers why, and
what to do when you need those keys back.
Reducing into a Map
A Map sidesteps the index-signature problem entirely, because Map.get already returns
V | undefined without any compiler flag:
const countryIndex = visitors.reduce((index, visitor) => {
const existing = index.get(visitor.country) ?? []
existing.push(visitor)
return index.set(visitor.country, existing)
}, new Map<string, Visitor[]>())
// countryIndex: Map<string, Visitor[]>No type argument is needed here: new Map<string, Visitor[]>() is already a typed value, so
inference has something real to work with. set returns the map, which is why the callback body
folds into a single return.
This is the general escape hatch. Whenever the accumulator has a constructor that takes its own type
arguments — Map, Set, a class of your own — build it with those arguments and the {} problem
never comes up.
Async callbacks do not work
One more trap, because it looks like it should work:
const sessionLengths = [120, 300, 45]
const asyncTotal = sessionLengths.reduce(async (running, length) => {
const previous = await running
return previous + length
}, Promise.resolve(0))
// asyncTotal: Promise<number>That one is actually correct — the accumulator is a promise, and each pass awaits the previous one.
It also runs every step in sequence, which is usually not what the person writing it wanted. If the
work per element is independent, map into an array of promises and hand it to
Promise.all instead. If it genuinely has to be sequential, a for...of
loop with await in the body is clearer than a promise-chaining fold.
The version that breaks is the one without await running, and it does not break silently.
Dropping the await means adding the promise itself, and TypeScript rejects that outright:
error TS2365: Operator '+' cannot be applied to types 'Promise<number>' and 'number'. The
accumulator type is pinned to Promise<number> by the initial value, so the compiler sees exactly
what is wrong. If you force it through anyway — an as any, or the same code in plain JavaScript —
the result is not NaN either: + stringifies the promise, so the fold resolves to the string
"[object Promise]45". Both failure modes are loud once you look; the trap is assuming the await
is optional because the callback is already async.
When not to use reduce
reduce is the most general array method, which is exactly why it is so often the wrong one. Three
cases where something else is clearer and types better with no effort:
Flattening. Use flatMap, not a reduce with concat.
const nestedTags = [['ts', 'js'], ['node'], []]
const flatTags = nestedTags.flatMap((tagGroup) => tagGroup)
// string[] — no accumulator, no type argument, no thought requiredRight to left. reduceRight has the identical three overloads and the identical inference
rules, so everything on this page applies to it unchanged. It is worth reaching for only when the
fold is genuinely order-dependent — composing functions, or building a nested structure from a flat
list back to front. If the order does not matter, use reduce, because readers assume left to
right and will not check.
A boolean answer. Use some or every. A fold into boolean works, but
javascript some says what you mean and short-circuits.
Building something complex. A for...of loop with a const accumulator is not a failure of
nerve. It allows early break, it gives you a real statement body, and the accumulator type is
whatever you declared it to be:
const visitorLoopCount: Record<string, number> = {}
for (const visitor of visitors) {
visitorLoopCount[visitor.country] = (visitorLoopCount[visitor.country] ?? 0) + 1
}No overloads, no inference puzzle, no type argument. Reach for reduce when the fold is genuinely
a single expression; reach for the loop when it is not.
TypeScript reduce: the short version
TypeScript reduce has exactly one gotcha, wearing several costumes. The accumulator type comes from
the initial value, so an untyped {} or [] gives you {} or never[] and every line after it
goes red.
- Always pass an initial value — the no-initial-value overload type-checks and then throws on an empty array.
- Prefer
reduce<U>(callback, initial)over asserting the initial value withas. - Treat every index read on a
Recordaccumulator as possiblyundefined, and turn onnoUncheckedIndexedAccessso the compiler agrees with you. - If the fold is not one expression, write the loop. The array methods are there to make code clearer, not shorter.
Become a TypeScript Pro
Track your progress through 200+ hands-on challenges. Free, sign in with GitHub.
Or start solving right away: explore all TypeScript challenges