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、

相关推荐
WEI_Gaot4 小时前
TS 为什么使用ts 和 创建ts的环境
前端·typescript
WEI_Gaot4 小时前
TS 的类型注解大全
前端·typescript
洛小豆10 小时前
深入理解 JavaScript 的解构赋值
前端·javascript·typescript
三棵杨树10 小时前
TypeScript从零开始(六):类
前端·typescript
鑫不想说话1064761 天前
ts+vue3出乎意料的推导报错
vue.js·typescript
RxnNing1 天前
http、https、TLS、证书原理理解,对称加密到非对称加密问题,以及对应的大致流程
前端·网络协议·学习·http·https·typescript
宇宙的有趣1 天前
当 TypeScript 类型嵌套超过了 100 层
前端·typescript
Jackson__2 天前
面试官:谈一下在 ts 中你对 any 和 unknow 的理解
前端·typescript
Dragon Wu2 天前
前端 React 弹窗式 滑动验证码实现
前端·javascript·react.js·typescript·前端框架·reactjs