react-i18next - 与 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>;
}
我不希望我们作为开发人员知道不同的命名空间,只是为了处理一组合并的键。任何帮助将非常感激。
解决方案
根据: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;
}
}
推荐阅读
- reactjs - 从 React 中的另一个文件修改状态
- r - 是否可以使用分位数回归找到预测区间?
- django - 为什么我的表单错误没有显示在模板中?
- sql - 带有输入参数的 SAP HANA 查询的语法
- python - 如何使用re搜索和匹配带括号的字符串?
- python - 尝试使用 for 循环绘制 matplotlib 散点图时出现错误?
- apache-poi - xmlbeans:深度等于未实现
- android - 为什么我无法删除 Android 中操作栏和主屏幕之间的分隔线?
- javascript - 好的,我有一个任务,我需要做这样的事情: obj.function().function().function() JavaScript
- json - Angular:显示 InfluxDB API 的结果