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、

相关推荐
fbincon8 小时前
Claude Code 自定义状态栏工具:安装、配置与 Subagent 状态展示
python·typescript·claude·claude-code·statusline
何何____15 小时前
TypeScript 函数类型兼容性
前端·javascript·typescript
VimorphTech18 小时前
React 任务轮询,为什么不能只写一个 setInterval?
javascript·typescript
const_qiu2 天前
第二章 2.6:初始化 NestJS 服务端 —— TypeScript 后端框架体验
前端·javascript·typescript
RobinDevNotes2 天前
一套代码发布到十几个平台:Cocos入门速览
typescript·c#·游戏开发
前端小L3 天前
typescript基础
typescript
濮水大叔3 天前
CabloyJS 的 AI 时刻:从 TypeScript 全栈框架到 AI 规范驱动开发
typescript·ai编程·全栈
程序员Sunday3 天前
TypeScript 的 any、unknown、never 有什么区别?
前端·面试·typescript
三十而立洋3 天前
TypeScript 7.0 深度解析:新特性、Go 原生编译器及与 TypeScript 6.0 的区别
前端·typescript·前端工程化
VimorphTech3 天前
React 自动保存怎么设计?防抖、串行请求与导出前等待
后端·typescript