Typing Reduce Accumulators Explicitly

Pass an explicit accumulator type to reduce when the initial value cannot carry it, so never[] widening is caught and Record or Map builders type-check.

TypescriptData Integrity

Code

typescriptsnippet
22 lines
const names = ["ada", "grace", "linus"];

// 初始值 [] 推断不出元素类型:acc 会被宽化成 never[],
// acc.push(name.length) 在类型层直接报错(注释保留失败形态)
// const lens = names.reduce((acc, name) => { acc.push(name.length); return acc; }, []);

// 第一个类型参数显式声明累加器(accumulator)形状:reduce<number[]>
const lens = names.reduce<number[]>((acc, name) => {
  acc.push(name.length);
  return acc;
}, []);

// 累加器是 Map 时同理:reduce<Map<string, number>>
const tags = ["ts", "ts", "go", "ts"];
const counts = tags.reduce<Map<string, number>>((acc, tag) => {
  acc.set(tag, (acc.get(tag) ?? 0) + 1);
  return acc;
}, new Map());

console.log(lens);        // [3, 5, 5]
console.log([...counts]); // [["ts", 3], ["go", 1]]

Output

Captured from a sandboxed run of this snippet in the build pipeline.

[ 3, 5, 5 ]
[ [ 'ts', 3 ], [ 'go', 1 ] ]

How the code works

Everything operates on top-level bindings: names, lens, tags, counts.

Points of care

  • Nothing is imported beyond what the runtime already provides.

Key statements

const counts = tags.reduce<Map<string, number>>((acc, tag) => {
acc.set(tag, (acc.get(tag) ?? 0) + 1);
return acc;
}, new Map());
const lens = names.reduce<number[]>((acc, name) => {
acc.push(name.length);
return acc;
}, []);

Interactive Tools for This Topic

FAQ

Anything to download besides the language toolchain?
Nothing beyond the toolchain you already have for this language. Its state lives in module-level bindings: `names`, `lens`, `tags`.