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

Typescript使用reduce封装对象方法返回Promise类型定义问题求助

修复后的完整可运行代码

const actions = {
  getSomething: ({ id }: { id: number }) => ({
    url: `/something/${id}`
  })
};

// 定义Action到Client方法的类型映射
type ActionClient<T extends Record<string, (...args: any) => any>> = {
  [K in keyof T]: (
    params: Parameters<T[K]>[0],
    options?: Record<string, any>
  ) => Promise<unknown>
}

function buildClient() {
  // 修正apiDispatch的类型定义,async函数本身返回Promise,可根据实际业务调整返回值泛型
  const apiDispatch = async (data: any): Promise<unknown> => {
    // 此处填写实际请求逻辑,比如fetch/axios调用
    return fetch(data.url, data.options)
  };

  return Object.entries(actions).reduce((acc, [key, value]) => {
    // 把key断言为原actions的键类型,解决索引报错
    const actionKey = key as keyof typeof actions
    acc[actionKey] = (data, options) =>
      apiDispatch({
        ...value(data),
        ...options
      });
    return acc;
    // 初始值断言为映射后的Client类型,不要用typeof actions
  }, {} as ActionClient<typeof actions>);
}

const client = buildClient();

// 此时调用会正确识别返回值为Promise,不会报then不存在的错误
client.getSomething({ id: 123 }).then((res) => res);

报错修复逻辑

  • 索引类型报错修复:
    你之前把reduce的初始值错误断言为typeof actions,而Object.entries返回的键默认是string类型,无法直接索引有固定键集合的对象。修复时新增了ActionClient泛型类型做方法映射,同时将遍历得到的key断言为原actions的键类型,彻底解决索引类型不匹配的问题。
  • then方法识别报错修复:
    原actions中的方法返回的是请求配置对象,不是Promise类型,你之前把返回的client断言为typeof actions,自然无法识别then方法。我们定义的ActionClient类型会遍历原actions的所有键,将每个方法改写为接收原参数+可选配置、返回Promise的函数,和实际封装后的逻辑完全匹配,调用时就能正确识别Promise类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 02:15:11