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、

相关推荐
千百元6 小时前
全栈开发技术组合
typescript·serverless
紫_龙7 小时前
最新版vue3+TypeScript开发入门到实战教程之组件通信之二
前端·javascript·typescript
木易 士心7 小时前
TypeScript 与 ArkTS 全面对比:鸿蒙生态下的语言演进
typescript·harmonyos
We་ct8 小时前
LeetCode 295. 数据流的中位数:双堆解法实战解析
开发语言·前端·数据结构·算法·leetcode·typescript·数据流
We་ct15 小时前
LeetCode 67. 二进制求和:详细题解+代码拆解
前端·数据结构·算法·leetcode·typescript
这是个栗子1 天前
关于 TypeScript 的介绍
前端·javascript·typescript
LXXgalaxy1 天前
Vue3 + TypeScript 组件开发速查表新手速成手册
前端·javascript·typescript
belldeep1 天前
前端:TypeScript 版本 2 , 3 , 4 , 5 , 6 有什么差别?
前端·javascript·typescript
烛衔溟2 天前
TypeScript 类型别名、字面量类型、联合类型与交叉类型
前端·javascript·typescript·联合类型·类型别名·字面量类型·交叉类型
烛衔溟2 天前
TypeScript 特殊类型与空值安全
安全·typescript·前端开发·空值处理