与 t useTranslation hook 一起使用时键入键

时间:2021-05-17 18:51:49

标签: react-i18next

我试图通过 useTranslation 钩子为 t 函数的使用带来类型安全。我已经看到以下线程扩展了资源界面,但我认为这不是我想要做的。

https://github.com/i18next/react-i18next/issues/1280

我想做的是:

// namespaces - A, B, both have key "hello"

import { useTranslation, TranslationKeys } from 'react-i18next';

export function Blah() {
  const { t } = useTranslation();

  return <div>{t(TranslationKeys.hello)}</div>;
}

我不希望我们作为开发人员知道不同的命名空间,只是为了处理单个合并的键集。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

根据:https://react.i18next.com/latest/typescript#create-a-declaration-file

我们有 3 个命名空间——sport、common 和 stuff,按重要到最不重要的顺序排列。

对于 TS 类型,我们只是将内容合并到 sport 命名空间中,这也是默认的命名空间,这做得很好。

declare module 'react-i18next' {
  interface Resources {
    'sport': typeof sport & typeof common & typeof stuff;
  }
}