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

React使用react-i18next返回对象触发Typescript错误如何解决?

react-i18next t函数返回对象TypeScript类型错误修复方案

报错核心原因:默认react-i18next的t函数类型定义默认返回值为string类型,即使传入returnObjects: true参数,默认类型声明也不会自动识别返回的对象结构,因此访问对象属性时会抛出Property 'xxx' does not exist on type 'string'的错误。

你可以根据场景选择以下任意一种方案修复:

方案1:临时类型断言(最快适配)

直接对返回的section变量做类型断言,适合快速修复局部问题:

const section = t(`ourmission:section`, {
  returnObjects: true
}) as {
  title: string;
  text: string;
  subtitle: string;
  list: Array<{name: string; pos: string}>;
};

方案2:使用t函数自带泛型

t函数本身支持传入泛型指定返回类型,比类型断言更规范:

const section = t<{
  title: string;
  text: string;
  subtitle: string;
  list: Array<{name: string; pos: string}>;
}>(`ourmission:section`, {
  returnObjects: true
});

方案3:全局声明多语言类型(一劳永逸,推荐)

在项目根目录或者types文件夹下新建i18next.d.ts类型声明文件,全局配置i18next的资源类型,后续所有调用t函数都会自动匹配类型:

import 'i18next';

declare module 'i18next' {
  interface CustomTypeOptions {
    // 禁止返回null
    returnNull: false;
    // 按你的多语言结构定义资源类型
    resources: {
      ourmission: {
        section: {
          title: string;
          text: string;
          subtitle: string;
          list: Array<{ name: string; pos: string }>;
        };
        // 可继续添加当前命名空间下其他多语言key的类型
      };
      // 可继续添加其他命名空间的类型定义
    };
  }
}

配置完成后重启TS服务,原代码不需要加任何额外类型声明就可以正常识别section的属性类型。

如果不需要严格类型校验,也可以用通用类型简化写法:

const section = t<Record<string, any>>(`ourmission:section`, { returnObjects: true });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 22:06:00