使用TypeScript对react-i18next做模块扩展时提示useTranslation未导出
问题原因
你同时声明了两个react-i18next的模块扩充块,分别对应不同版本的类型定义规则,在TS4.4版本下会触发类型合并异常,覆盖了react-i18next原本的导出成员定义,导致useTranslation等导出成员识别失败。
解决方案
1. 匹配版本保留对应声明块
先确认你使用的react-i18next版本,只保留对应版本的声明块即可:
- 若使用v11.11.0及以上版本:仅保留
CustomTypeOptions的扩充块,删除Resources接口的扩充块 - 若使用v11.11.0以下版本:仅保留
Resources接口的扩充块,删除CustomTypeOptions的扩充块
2. 替换为正确的声明文件内容
以v11.11.0及以上版本为例,完整的react-i18next.d.ts内容如下:
// 导入原有类型定义 import 'react-i18next'; // 导入默认语言的命名空间文件 import translation from 'locales/en/translation.json'; import toast from 'locales/en/toasts.json'; declare module 'react-i18next' { interface CustomTypeOptions { defaultNS: 'translation'; resources: { translation: typeof translation; toast: typeof toast; }; } }
若使用v11.11.0以下版本,内容如下:
// 导入原有类型定义 import 'react-i18next'; // 导入默认语言的命名空间文件 import translation from 'locales/en/translation.json'; import toast from 'locales/en/toasts.json'; declare module 'react-i18next' { interface Resources { translation: typeof translation; toast: typeof toast; } }
3. 额外排查项
- 确认
tsconfig.json的include配置包含了声明文件的存放路径,例如声明文件放在src目录下,需保证include数组包含"src/**/*"规则 - 确认已卸载额外安装的
@types/react-i18next包,v11及以上版本的react-i18next自带官方类型定义,额外安装社区类型包会引发冲突 - 修改完成后重启TS语言服务即可生效,VSCode中可通过快捷键
Ctrl+Shift+P(Mac为Cmd+Shift+P),选择「TypeScript: Restart TS Server」执行重启
内容的提问来源于stack exchange,提问作者Danielo515
相关产品推荐
相关产品推荐

