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

在TypeScript中使用i18next:如何让t函数支持命名空间前缀键

解决i18next TypeScript类型支持命名空间前缀键的问题

要让t('common:auth.login.text')这种带命名空间前缀的写法获得类型检查支持,需要修改i18next.d.ts的类型定义,扩展t函数的键类型,使其兼容[命名空间]:[键]的格式。

步骤1:定义联合类型的前缀键

先把所有命名空间和对应键组合成NS:Key格式的联合类型,替换原来的资源类型定义方式:

import 'i18next';
import common from '../public/locales/en/common.json';

// 定义单个命名空间的前缀键类型
type PrefixKeys<NS extends string, T> = `${NS}:${Extract<keyof T, string>}`;

// 组合所有命名空间的前缀键
type AllPrefixedKeys = PrefixKeys<'common', typeof common>;

// 同时保留默认命名空间的无前缀键
type AllKeys = keyof typeof common | AllPrefixedKeys;

declare module 'i18next' {
  interface CustomTypeOptions {
    returnNull: false;
    defaultNS: 'common';
    // 覆盖resources的类型,同时扩展键的类型
    resources: {
      common: typeof common;
    };
    // 自定义t函数的键类型
    keyPrefix: '';
    keys: AllKeys;
  }
}

步骤2:多命名空间场景扩展(可选)

如果后续添加其他命名空间(比如auth),只需扩展类型定义即可:

import 'i18next';
import common from '../public/locales/en/common.json';
import auth from '../public/locales/en/auth.json';

type PrefixKeys<NS extends string, T> = `${NS}:${Extract<keyof T, string>}`;
type AllPrefixedKeys = PrefixKeys<'common', typeof common> | PrefixKeys<'auth', typeof auth>;
type AllKeys = keyof typeof common | keyof typeof auth | AllPrefixedKeys;

declare module 'i18next' {
  interface CustomTypeOptions {
    returnNull: false;
    defaultNS: 'common';
    resources: {
      common: typeof common;
      auth: typeof auth;
    };
    keyPrefix: '';
    keys: AllKeys;
  }
}

关键说明

  • 通过PrefixKeys工具类型自动生成NS:Key格式的键,无需手动维护所有前缀组合
  • AllKeys合并了默认命名空间的无前缀键和所有带前缀的键,兼容两种写法逻辑
  • 保留原有defaultNS配置,不影响t('auth.login.text')(默认命名空间)或t('auth:xxx')(前缀指定)的既有用法

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 01:43:31