typescript - 将 i18next 与 TypeScript 结合使用 : How to Support Prefixed Namespace Keys in the t Function

标签 typescript next.js i18next react-i18next next-i18next

我正在使用i18next使用 typescript 并使用 i18next-resources-for-ts 的翻译资源从 JSON 生成资源类型。一切正常,但在使用带有 useTranslation() Hook 中的 t 函数的前缀命名空间时遇到问题。我不是在寻找 useTranslation('common')t('auth.login.text', { ns: 'common' }),它工作正常并且是输入正确。

这是我的 i18next.d.ts 的简化版本:

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

const resources = {
  common,
} as const;

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

并设置i18next.ts

import commonDe from '../public/locales/de/common.json';
import commonEn from '../public/locales/de/common.json';
import i18next from 'i18next';
import { initReactI18next } from 'react-i18next';

const resources = {
  de: {
    common: commonDe,
  },
  en: {
    common: commonEn,
  },
};

export const defaultNS = 'common';

i18next
  .use(initReactI18next)
  .init({
    resources,
    ns: [defaultNS],
    defaultNS,
    lng: 'en',
    interpolation: {
      escapeValue: false,
    },
    returnNull: false,
  });

export default i18next;

尝试在 t 函数中使用前缀命名空间时会出现问题:

const { t } = useTranslations();
t('common:auth.login.text')

然后类型不起作用。

我知道我可以指定 ns 作为 t 函数的选项,或者在 useTranslation Hook 中选择它。但我也想在翻译键中支持上面的前缀方式。

任何有关如何实现这一目标的建议或想法将不胜感激。谢谢!

最佳答案

这并不是真正关于i18next-resource-for-ts,而是关于react-i18next的工作方式。

i18next中,这会很好用:

// when you call i18next directly,
i18next.t('common:auth.login.text'); // work fine, not recommended, but what you want specifically.
i18next.t('auth.login.text', { ns: 'common' }); // work fine too.

但是,使用 react-i18next 时,您必须使用 useTranslation() 三种方法为多个翻译文件指定命名空间 >、withTranslation()Translation(如 documentation 中所述):

// when you call react-i18next methods,
const { t } = useTranslations();
t('common:auth.login.text'); // fail.

当这三个方法不带参数传递时,它会识别 i18next.ts 文档中指定的默认命名空间。但是,每当您想在 t 函数中指定命名空间时,最好按如下方式执行:

const { t } = useTranslation('common'); // and when you have multiple, put all of them in an array.
t('common:auth.login.text'); // would work fine.

希望以上回答对您有所帮助。

关于typescript - 将 i18next 与 TypeScript 结合使用 : How to Support Prefixed Namespace Keys in the t Function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77665321/

相关文章:

html - 我需要 i18next-xhr-backend 才能在分离的 json 文件中使用翻译吗?

javascript - "Unexpected token import" Angular 2外部模块

promise.reject 的 TypeScript 类型定义

typescript - 也许是 typescript 中的一种类型

reactjs - NextJS + React 上下文 : How to load data?

javascript - 传入样式表作为功能组件中渲染的 Prop

javascript - 为什么 styled-components 将我的属性添加到 DOM 中?

react-native - I18n 在任何混合应用程序中支持多种语言

aurelia - 在 aurelia i18N 中使用多个翻译文件

typescript - 将通用参数传递给 typescript 声明文件中的 React.FunctionComponent