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

TypeScript数组reduce累加器类型定义报错问题求助

解决TypeScript中reduce累加器的类型报错问题

问题原因

报错的核心在于reduce方法的初始值{}被TypeScript默认推断为空对象类型{},即便你给累加器参数acc标注了Partial<IWithdrawalRequest>,初始值的类型与参数类型不匹配,导致TypeScript认为acc[key]只能是undefined,无法兼容payoutFields[key]的string | number类型。

解决方案

方案1:给初始值显式指定类型

直接通过类型断言给初始值{}指定Partial<IWithdrawalRequest>类型,让初始值与累加器参数的类型保持一致:

private buildRequestBody(payoutFields: IWithdrawalRequest): ISignedWithdrawalRequest {
  const sortedPayoutFieldKeys = Object.keys(payoutFields)
    .sort() as Array<keyof IWithdrawalRequest>;

  const requestBody = sortedPayoutFieldKeys.reduce((acc: Partial<IWithdrawalRequest>, key) => {
    acc[key] = payoutFields[key];
    return acc;
  }, {} as Partial<IWithdrawalRequest>); // 显式指定初始值类型

  ...
}

方案2:使用reduce的泛型参数明确累加器类型

通过reduce<Partial<IWithdrawalRequest>>的泛型声明,直接告诉TypeScript累加器的类型,无需单独给acc参数标注类型:

private buildRequestBody(payoutFields: IWithdrawalRequest): ISignedWithdrawalRequest {
  const sortedPayoutFieldKeys = Object.keys(payoutFields)
    .sort() as Array<keyof IWithdrawalRequest>;

  const requestBody = sortedPayoutFieldKeys.reduce<Partial<IWithdrawalRequest>>((acc, key) => {
    acc[key] = payoutFields[key];
    return acc;
  }, {});

  ...
}

补充说明

  • Partial<IWithdrawalRequest>会将IWithdrawalRequest的所有属性转为可选类型,完美匹配初始空对象的状态,同时允许逐步赋值。
  • 如果后续需要将requestBody转为完整的IWithdrawalRequest,可以在后续逻辑中使用类型断言(如requestBody as IWithdrawalRequest),前提是你能确保所有必要属性都已被赋值。

内容的提问来源于stack exchange,提问作者Vahagn Sargsyan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 16:40:40