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

RTK Query自动生成Hook遇TypeScript错误(TS2742)求助

RTK Query自动生成Hook触发TS2742错误的解决方案

问题详情

我按照RTK Query官方文档编写代码,实现了Pokemon数据查询接口:

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
import type { Pokemon } from './types'

// 定义API服务
export const pokemonApi = createApi({
  reducerPath: 'pokemonApi',
  baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
  endpoints: (builder) => ({
    getPokemonByName: builder.query<Pokemon, string>({
      query: (name) => `pokemon/${name}`,
    }),
  }),
})

// 导出自动生成的Hook
export const { useGetPokemonByNameQuery } = pokemonApi

但在使用useGetPokemonByNameQuery时,遇到TypeScript错误:

The inferred type of 'useGetPokemonByName1Query' cannot be named
without a reference to
'../../../node_modules/@reduxjs/toolkit/dist/query/react/buildHooks'.
This is likely not portable. A type annotation is necessary.ts(2742)

我的项目依赖版本如下:

"dependencies": {
    "@emotion/react": "^11.11.4",
    "@emotion/styled": "^11.11.5",
    "@fontsource/roboto": "^5.0.13",
    "@mui/icons-material": "^5.15.20",
    "@mui/material": "^5.15.20",
    "@reduxjs/toolkit": "^2.2.5",
    "react": "^18.3.1",
    "react-dom": "^18.3.1",
    "react-redux": "^9.1.2",
    "uuid": "^10.0.0"
  },
  "devDependencies": {
    "@types/react": "^18.3.3",
    "@types/react-dom": "^18.3.0",
    "@types/uuid": "^10.0.0",
    "@typescript-eslint/eslint-plugin": "^7.13.1",
    "@typescript-eslint/parser": "^7.13.1",
    "@vitejs/plugin-react": "^4.3.1",
    "eslint": "^8.57.0",
    "eslint-plugin-react-hooks": "^4.6.2",
    "eslint-plugin-react-refresh": "^0.4.7",
    "typescript": "^5.2.2",
    "vite": "^5.3.1"
  }

可行解决方案

1. 显式为Hook添加类型标注

导入RTK Query提供的Hook类型,手动标注导出的Hook:

import { createApi, fetchBaseQuery, UseQueryHook } from '@reduxjs/toolkit/query/react'
import type { Pokemon } from './types'

// 保持原有API定义不变

// 显式指定Hook类型
export const useGetPokemonByNameQuery: UseQueryHook<Pokemon, string> = pokemonApi.useGetPokemonByNameQuery

2. 调整TypeScript配置

在tsconfig.json中修改编译器选项,解决类型推断路径问题:

{
  "compilerOptions": {
    "preserveSymlinks": true,
    "skipLibCheck": true,
    "declaration": false
  }
}
  • preserveSymlinks: 保留模块符号链接,避免TypeScript解析路径时出现歧义
  • skipLibCheck: 跳过第三方库的类型检查,减少隐式类型冲突
  • declaration: 若项目不需要发布类型声明文件,关闭该选项可避免导出隐式类型的问题

3. 依赖版本更新或兼容性检查

尝试升级RTK到最新稳定版,或确认react-redux与RTK版本匹配:

npm update @reduxjs/toolkit react-redux

当前react-redux@9.1.2与RTK 2.x版本兼容,但小版本补丁可能修复类型推断的细节问题。

4. 调整Hook导出方式

避免直接解构导出,改用以下方式:

// 方案1: 导出整个API对象,组件中直接调用api.useGetPokemonByNameQuery
export default pokemonApi

// 方案2: 使用类型断言绕过推断问题
export const useGetPokemonByNameQuery = pokemonApi.useGetPokemonByNameQuery as typeof pokemonApi.useGetPokemonByNameQuery

内容的提问来源于stack exchange,提问作者Nguyễn Ngọc Hải

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 20:33:11