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、

相关推荐
能来帮帮蒟蒻吗2 天前
VUE3 -综合实践(Mock+Axios+ElementPlus)
前端·javascript·vue.js·笔记·学习·ajax·typescript
菜鸟una3 天前
【taro3 + vue3 + webpack4】在微信小程序中的请求封装及使用
前端·vue.js·微信小程序·小程序·typescript·taro
struggle20253 天前
continue通过我们的开源 IDE 扩展和模型、规则、提示、文档和其他构建块中心,创建、共享和使用自定义 AI 代码助手
javascript·ide·python·typescript·开源
Bl_a_ck3 天前
【React】Craco 简介
开发语言·前端·react.js·typescript·前端框架
Bl_a_ck4 天前
开发环境(Development Environment)
开发语言·前端·javascript·typescript·ecmascript
菜鸟una4 天前
【layout组件 与 路由镶嵌】vue3 后台管理系统
前端·vue.js·elementui·typescript
浪裡遊5 天前
Typescript中的对象类型
开发语言·前端·javascript·vue.js·typescript·ecmascript
从味书5 天前
安装typescript时,npm install -g typescript报错
javascript·typescript·npm
風吹过7 天前
A* (AStar) 寻路
typescript·cocos2d
geovindu7 天前
vue3: pdf.js 2.16.105 using typescript
javascript·vue.js·typescript·pdf