使用i18next和TypeScript:如何在t函数中支持前缀空格键

dfuffjeb  于 5个月前  发布在  TypeScript
关注(0)|答案(1)|浏览(68)

我正在使用i18next和typescript,并使用i18next-resources-for-ts从JSON和翻译资源生成资源类型。一切都很好,但我在使用useTranslation()钩子中的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钩子中选择它。但我也想在翻译键中支持如上所述的前缀方式。
任何关于如何实现这一目标的建议或想法将不胜感激。谢谢!

fzsnzjdm

fzsnzjdm1#

这不是真正的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三种方法为多个翻译文件指定namespace(s)(如documentation中所述):

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


当这三个方法没有参数传递时,它识别i18next.ts文档中指定的默认namespace。但是,每当你想在t函数中指定namespace(s)时,最好像下面这样执行:

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


希望上面的回答能有所帮助。

相关问题