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

扩展RTK Query的MutationExtraOptions泛型接口遇TS提示问题

解决RTK Query扩展MutationExtraOptions后类型提示不生效的问题

修复步骤

1. 调整声明文件位置与TS配置

  • 将类型声明代码放在项目根目录的types文件夹下(如types/rtk-query.d.ts),或src目录下的global.d.ts中。
  • 确保tsconfig.json的include配置包含这些文件:
    {
      "include": ["src/**/*", "types/**/*"]
    }
    

2. 对齐泛型参数并扩展核心模块接口

RTK Query的MutationExtraOptions核心定义在@reduxjs/toolkit/query模块,需同时扩展核心模块与react模块的接口,确保类型合并生效:

import type { BaseQueryFn } from '@reduxjs/toolkit/query';

declare module '@reduxjs/toolkit/query' {
  export interface MutationExtraOptions<
    TagTypes extends string,
    ResultType,
    QueryArg,
    BaseQuery extends BaseQueryFn,
    ReducerPath extends string = string
  > {
    optimisticUpdates?: ((args: QueryArg) => any[])[];
  }
}

declare module '@reduxjs/toolkit/query/react' {
  export interface MutationExtraOptions<
    TagTypes extends string,
    ResultType,
    QueryArg,
    BaseQuery extends BaseQueryFn,
    ReducerPath extends string = string
  > {
    optimisticUpdates?: ((args: QueryArg) => any[])[];
  }
}

3. 重启TypeScript语言服务

VS Code的TS服务可能缓存旧类型,按Ctrl+Shift+P(Windows)/Cmd+Shift+P(Mac),输入TypeScript: Restart TS Server重启服务。

4. 验证useMutation调用

确保调用useMutation时正确传入extraOptions:

const { mutate } = useMutation({
  query: (arg) => ({ /* 请求配置 */ }),
  extraOptions: {
    optimisticUpdates: [(args) => { /* 乐观更新逻辑 */ }]
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 21:46:09