You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript自定义对象类型未继承原生对象方法,如何解决?

问题原因与解决方案

首先明确:reduce是数组的方法,JavaScript里普通键值对对象的原型(Object.prototype)本身就没有reduce,TypeScript只是如实反映了这个JS的实际行为,所以你的自定义类型A作为普通对象,自然没有这个方法。

要实现遍历对象并做类似reduce的聚合操作,有两种常规方式:

1. 把对象转换为数组后使用reduce

用Object.entries、Object.keys或Object.values把对象转换成数组,再调用reduce:

type A = {
  readonly prop1: string;
  readonly prop2: string;
}

const getStuff = (obj: A) => {
  // Object.entries返回[key, value]格式的数组
  return Object.entries(obj).reduce((acc, [key, value]) => {
    // 这里写你的聚合逻辑,比如把值转为大写后存入累加器
    acc[key] = value.toUpperCase();
    return acc;
  }, {} as Record<string, string>);
}

如果只需要处理键或者值,也可以用Object.keys(obj)或Object.values(obj)生成对应数组后再reduce。

2. 手动给自定义类型添加reduce方法(不推荐)

如果一定要让A类型拥有reduce方法,可以手动定义,但这种方式不符合JS的常规写法,除非有特殊需求:

type A = {
  readonly prop1: string;
  readonly prop2: string;
  // 定义reduce方法的类型
  reduce: <T>(callback: (acc: T, curr: [string, string]) => T, initialValue: T) => T;
}

// 使用时需要给对象实现这个方法
const objWithReduce: A = {
  prop1: "foo",
  prop2: "bar",
  reduce(callback, initialValue) {
    return Object.entries(this).reduce(callback, initialValue);
  }
}

const getStuff = (obj: A) => {
  return obj.reduce((acc, [key, value]) => {
    acc[key] = value.length;
    return acc;
  }, {} as Record<string, number>);
}

一般来说第一种方式是更通用、更符合JS/TS习惯的解决方案。

内容的提问来源于stack exchange,提问作者benjamin.keen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 23:41:05