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、

相关推荐
天下无贼!8 小时前
2024年最新版TypeScript学习笔记——泛型、接口、枚举、自定义类型等知识点
前端·javascript·vue.js·笔记·学习·typescript·html
Jorah2 天前
1. TypeScript基本语法
javascript·ubuntu·typescript
小白小白从不日白3 天前
TS axios封装
前端·typescript
aimmon4 天前
Superset二次开发之源码DependencyList.tsx 分析
前端·typescript·二次开发·bi·superset
下雪天的夏风4 天前
Vant 按需引入导致 Typescript,eslint 报错问题
前端·typescript·eslint
theMuseCatcher5 天前
Vue3+TypeScript+Vite+Less 开发 H5 项目(amfe-flexible + postcss-pxtorem)
typescript·less·postcss
Qiyandays5 天前
vue + Lodop 制作可视化设计页面 实现打印设计功能(四)
前端·vue.js·typescript
人工智能的苟富贵5 天前
微信小程序中的模块化、组件化开发:完整指南
微信小程序·小程序·typescript
Code blocks7 天前
小试牛刀-区块链Solana多签账户
算法·typescript·区块链·github
shiming88797 天前
Vue 生命周期与 TypeScript:深入理解组件生命周期
前端·vue.js·typescript