我正在尝试使react-i18next与打字稿一起工作,但即使代码工作正常,我的编辑器上也会出现打字稿警告。
错误:
Argument of type '["button.add"]' is not assignable to parameter of type '[key: TemplateStringsArray | "en:button.add" | (TemplateStringsArray | "en:button.add")[], options?: TOptionsBase & $Dictionary & InterpolationMap<...>] | [key: ...] | [key: ...]'.
对于上下文,我使用 React-i18next 13.5.0、I18next 23.7.6、Typescript 5.2.2
我的
i18n.ts
:
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import en from "../locale/en.json";
import vi from "../locale/vi.json";
export const resources = {
en: {
translation: en,
},
vi: {
translation: vi,
},
};
i18n.use(initReactI18next).init({
resources,
lng: "en",
interpolation: {
escapeValue: false,
},
});
export default i18n;
i18n.d.ts
:
import resources from "./i18n-resources";
declare module "i18next" {
interface CustomTypeOptions {
resources: { en: (typeof resources)["en"] };
}
}
i18n-resources.ts
:
import en from '../locale/en.json';
import vi from '../locale/vi.json';
const resources = {
en,
vi
} as const;
export default resources;
简化
en.json
:
{
button: {
add: "Add"
}
}
简化使用:
import { useTranslation } from "react-i18next";
const Usage = () => {
const { t } = useTranslation();
return (
<div>{t("button.add")}</div>
);
};
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import { en } from "../locale/en.json"; // Import as JSON object
import { vi } from "../locale/vi.json"; // Import as JSON object
export const resources = {
en: {
translation: en,
},
vi: {
translation: vi,
},
};
i18n.use(initReactI18next).init({
resources,
lng: "en",
interpolation: {
escapeValue: false,
},
});
export default i18n;
并对 en.json 和 vi.json 文件进行以下更改,以将翻译导出为 JSON 对象:
// en.json
{
"button": {
"add": "Add"
}
}
// vi.json
{
"button": {
"add": "Thêm"
}
}