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

如何让mutationFactory的invalidate参数正确推断对应API方法返回类型?

解决mutationFactory中invalidate参数的自动类型推断问题

问题核心在于当前mutationFactory的类型定义未将invalidate参数与选中的API方法做绑定,导致它提示所有API方法的返回类型联合。要解决这个问题,只需调整泛型约束,让invalidate的参数类型严格对应当前传入的API方法的Awaited返回类型。

修改后的函数类型定义示例

// 假设你的API类型定义如下
type ApiService = {
  updateUser: (payload: { id: number; name: string }) => Promise<{ id: number; name: string; updatedAt: Date }>;
  deleteArticle: (id: number) => Promise<{ success: boolean; message: string }>;
};

function mutationFactory<Api extends Record<string, (...args: any[]) => Promise<any>>>(api: Api) {
  // 将泛型约束到具体的API方法键,而非整个API对象
  return function createMutation<Method extends keyof Api>(options: {
    method: Method;
    // 直接关联当前Method对应的API方法的返回值类型
    invalidate?: (result: Awaited<Api[Method]>) => void;
  }) {
    // 你的mutation实现逻辑
    return async (params: Parameters<Api[Method]>[0]) => {
      const result = await api[options.method](params);
      options.invalidate?.(result);
      return result;
    };
  };
}

使用示例

const api: ApiService = {
  updateUser: (payload) => Promise.resolve({ ...payload, updatedAt: new Date() }),
  deleteArticle: (id) => Promise.resolve({ success: true, message: `Article ${id} deleted` })
};

const createMutation = mutationFactory(api);

// 这里invalidate的参数会自动推断为{ id: number; name: string; updatedAt: Date }
const updateUserMutation = createMutation({
  method: 'updateUser',
  invalidate: (user) => {
    console.log(user.updatedAt); // 类型提示正常,不会出现其他API的返回字段
  }
});

// 这里invalidate的参数自动推断为{ success: boolean; message: string }
const deleteArticleMutation = createMutation({
  method: 'deleteArticle',
  invalidate: (res) => {
    console.log(res.message); // 类型提示正常
  }
});

关键修改说明

  1. 将createMutation的泛型Method绑定到Api的具体方法键,确保TypeScript能追踪当前选中的是哪个API方法。
  2. 将invalidate的参数类型定义为Awaited<Api[Method]>,直接关联当前选中方法的异步返回值类型,而非所有API方法返回类型的联合。

这样修改后,当你选择不同的method时,invalidate的参数类型会自动匹配对应API方法的返回值,无需手动指定类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 11:52:33