首页 > 解决方案 > 与 t useTranslation 挂钩使用时键入键

问题描述

我试图从 useTranslation 钩子中为 t 函数的使用带来类型安全。我已经看到了在 Resources 接口上扩展的以下线程,但我认为这并不是我想要做的。

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>;
}

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

标签: react-i18next

解决方案


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

我们有 3 个命名空间——运动、普通和东西,按照从重要到最不重要的顺序排列。

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

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

推荐阅读