Workaround typesafe translations with useTranslation hook #179
Replies: 3 comments
-
@Cmoen11 |
Beta Was this translation helpful? Give feedback.
-
You can achieve the same if you add this to a import type * as resources from "../config/locales/en";
declare module "i18next" {
interface CustomTypeOptions {
resources: typeof resources;
}
} The Then when you call |
Beta Was this translation helpful? Give feedback.
-
Thanks for the handy hook @Cmoen11! I also use the import { useTranslation as _useTranslation, Trans as OriginalTrans, } from "react-i18next";
export const Trans = ({
i18nKey,
...props
}: Omit<React.ComponentProps<typeof OriginalTrans>, "i18nKey"> & {
i18nKey: KeysUnion<typeof translationEN>;
}) => {
return <OriginalTrans i18nKey={i18nKey} {...props} />;
}; Also, I noticed you don't pass the options from the import { TOptionsBase } from "i18next";
import { $Dictionary } from "node_modules/i18next/typescript/helpers";
const t = (
str: KeysUnion<typeof translationEN>,
options?: (TOptionsBase & $Dictionary) | undefined
) => translation.t(str, options); |
Beta Was this translation helpful? Give feedback.
-
I've written a hook that provides type safe strings with
.
seperated translations with the useTranslation hookSo instead of importing from react-i18next, you just import this instead. and you will have typesafe translations :)
Beta Was this translation helpful? Give feedback.
All reactions