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

TypeScript无法推断react-i18n useTranslation钩子类型求助

React-i18n useTranslation钩子TypeScript类型推断失效问题解决办法

问题重现

使用react-i18n的useTranslation钩子时,TypeScript无法自动推断与字典匹配的键类型,输入不存在的键也不会触发类型报错。已尝试配置自定义类型声明,但未生效。

相关代码如下:

业务组件代码

import { useTranslation } from 'react-i18next';

const { t } = useTranslation();

t('blabla'); // 期望输入错误键时TS报错,但当前无类型提示

英文字典文件(en.ts)

const en = { blabla: 'blabla' }

i18n配置文件

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';

import enTranslation from './en';

i18n.use(initReactI18next).init({
    resources: {
        en: {
            translation: enTranslation,
        },
    },
    lng: 'en',
    keySeparator: '.',
    interpolation: {
        escapeValue: false,
    },
});

export default i18n;

现有类型声明(@types/react-i18n/index.d.ts)

import 'react-i18next';

import type dictionary from '../../src/i18n/en';

declare module 'react-i18next' {
    interface CustomTypeOptions {
        resources: typeof dictionary;
    }
}

tsconfig.json核心配置

{
    "compilerOptions": {
        "baseUrl": "./",
        "typeRoots": ["./@types", "./node_modules/@types"],
        // 其他配置...
    }
}

核心问题排查

  1. 字典文件未正确导出:原en.ts仅声明了变量en,未通过export导出,导致类型声明文件无法正确获取其类型。
  2. 类型声明文件路径错误:原声明文件命名为@types/react-i18n/index.d.ts,但实际要扩展的是react-i18next模块,文件名需对应模块名。
  3. CustomTypeOptions配置不完整:新版本react-i18n要求明确指定defaultNS(默认命名空间),否则类型推断逻辑会失效。

解决方案步骤

1. 修正字典文件的导出

修改en.ts,添加导出语句:

export default { blabla: 'blabla' };

2. 修正类型声明文件

将@types/react-i18n/index.d.ts重命名为@types/react-i18next/index.d.ts,并更新配置内容:

import 'react-i18next';
// 确保导入路径与你的项目结构匹配
import type enTranslation from '../../src/i18n/en';

declare module 'react-i18next' {
  interface CustomTypeOptions {
    // 指定默认命名空间,与i18n配置中的translation对应
    defaultNS: 'translation';
    // 匹配resources的结构:语言 -> 命名空间 -> 字典内容
    resources: {
      translation: typeof enTranslation;
    };
  }
}

3. 验证TS配置有效性

确保tsconfig.json中的typeRoots包含./@types,且baseUrl设置正确,避免导入路径错误导致类型无法识别。

4. 重启TypeScript服务器

修改类型声明文件后,TS可能不会自动刷新,需要重启编辑器的TS服务(比如VSCode中按Ctrl+Shift+P,选择"TypeScript: Restart TS Server")。

验证效果

修改完成后,再次使用t函数时,输入不存在的键(比如t('wrong-key')),TypeScript会立即提示类型错误,实现预期的强类型检查效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 08:20:30