I'm trying to make react-i18next work with typescript, but I'm having a typescript warning on my editor even when the code is working fine.
The error:
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: ...]'.
For context I'm using React-i18next 13.5.0, I18next 23.7.6, Typescript 5.2.2
My 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;
Simplified en.json
:
{
"button": {
"add": "Add"
}
}
Simplified usage:
import { useTranslation } from "react-i18next";
const Usage = () => {
const { t } = useTranslation();
return (
<div>{t("button.add")}</div>
);
};
Edit: My work-around is to change my d.ts into
import resources from "./i18n-resources";
declare module "i18next" {
interface CustomTypeOptions {
resources: typeof resources["en"];
nsSeparator: ".";
}
}
But I really want to know why and how to fix this properly.