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

Vite+React+Babel使用ReturnType<typeof泛型函数>时TS报错求助

问题:Vite + React + TypeScript构建时ReturnType嵌套泛型语法报错

问题场景

我使用Vite、React和TypeStack开发应用,以下代码导致Vite构建失败:

export type UseSearchFilters<T> = ReturnType<typeof useSearchFilters<T>>

报错信息

[plugin:vite:react-babel] useSearchFilters.ts: Unexpected token, expected "," (6:68)

6 | export type UseSearchFilters = ReturnType<typeof useSearchFilters>

问题卡在最后的>符号——删除后TypeScript会提示缺少该符号,但保留的话Babel和Prettier都会报错。tsc单独编译正常,团队目前找不到解决思路。

当前依赖版本

{
  "@babel/core": "^7.16.7",
  "@babel/preset-env": "^7.16.8",
  "@babel/preset-react": "^7.16.7",
  "@babel/preset-typescript": "^7.16.7",
  "react": "^17.0.0",
  "react-dom": "^17.0.0",
  "typescript": "^4.3.2",
  "vite": "^3.0.4"
}

解决方案

1. 升级Babel TypeScript预设

你当前使用的@babel/preset-typescript@7.16.7对嵌套泛型的语法解析存在bug,升级到7.17.0及以上版本即可解决该问题,新版本已修复对ReturnType<typeof useSearchFilters<T>>这类写法的支持。

2. 临时规避写法(无需升级依赖)

如果暂时无法升级依赖,可以将嵌套泛型拆分为单独的类型别名,绕过Babel的解析问题:

// 先抽离函数类型
type SearchFiltersFunction<T> = typeof useSearchFilters<T>
// 再基于别名定义最终类型
export type UseSearchFilters<T> = ReturnType<SearchFiltersFunction<T>>

3. 对齐TypeScript与Babel配置

在tsconfig.json中补充以下配置,确保两者的语法解析规则一致:

{
  "compilerOptions": {
    "esModuleInterop": true,
    "skipLibCheck": true,
    "target": "ESNext",
    "moduleResolution": "Node"
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 09:10:44