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
相关产品推荐
相关产品推荐

