Array.reduce 的类型你会写吗?

How To Type Array.reduce

使用 reduce 的时候我们通常会遇到 TS 类型错误问题:

ts 复制代码
const array = [
  { key: "name", value: "Daniel" },
  { key: "age", value: "26" },
  { key: "location", value: "UK" },
];

const grouped = array.reduce((obj, item) => {
  obj[item.key] = item.value;
  return obj;
}, {});

第八行会报错:

matlab 复制代码
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.  
No index signature with a parameter of type 'string' was found on type '{}'.(7053)

你可以复制代码到 ts playground 尝试是否能解决。本文将提供三种解决方案。

为什么会报错

因为 obj 的类型是从 reduce 的第二个参数 {} 推导的,而 {} 类型等价于 Record<never, never>,即不能有任何 key 的对象,故不能 obj[item.key] = item.value;。解决思路是显示告诉其类型。

办法 1:用 as 强制断言

ts 复制代码
const grouped = array.reduce((obj, item) => {
  obj[item.key] = item.value;
  return obj;
}, {} as Record<string, string>);

办法 2:给参数加类型

ts 复制代码
const grouped = array.reduce(
  (obj: Record<string, string>, item) => {
    obj[item.key] = item.value;
    return obj;
  },
  {}
);

办法 3:给 reduce 增加泛型

ts 复制代码
const grouped = array.reduce<Record<string, string>>(
  (obj, item) => {
    obj[item.key] = item.value;
    return obj;
  },
  {}
);

我们通过查看 array.reduce 的 TS 类型源码可以得知其可以接受泛型。


翻译自 How To Type Array.reduce 作者是著名的 TS 解密大师 Matt Pocock、

相关推荐
用户0566949483112 小时前
🔥 我把 axios 接口封装,玩出了 NestJS 的感觉
typescript
索西引擎14 小时前
【理论】TypeScript 函数重载:从 Vue 3 defineEmits 说起的类型安全实践
前端·typescript
漫游的渔夫16 小时前
从 if-else 乱麻到状态机:前端开发者该怎么理解多 Agent 协作?
前端·人工智能·typescript
matrixmind817 小时前
sindresorhustype-fest:TypeScript 工具类型集合
前端·javascript·其他·typescript
guangzan1 天前
DeepSeek-Lane:在 Cursor 内使用 DeepSeek V4 模型
typescript
晓杰'2 天前
从0到1实现 Balatro 游戏后端(1):项目规划与牌型判断实现
后端·websocket·typescript·node.js·游戏开发·项目实战·nestjs
Forget the Dream2 天前
基于适配器模式的 Axios 封装实践
设计模式·typescript·axios·适配器模式
烛衔溟2 天前
TypeScript 接口继承与混合类型
linux·ubuntu·typescript
送鱼的老默2 天前
学习笔记--入门typescript直接案例开搞
前端·typescript
spmcor3 天前
TypeScript 中 null 与 undefined 的区别 —— 一篇彻底搞懂的指南
typescript