Home > Net >  TypeScript does not infer react-i18n "useTranslation" hook types
TypeScript does not infer react-i18n "useTranslation" hook types

Time:11-14

Using react-i18n, I use the useTranslation hook of this package:

import { useTranslation } from 'react-i18next';

const { t } = useTranslation();

t('blabla');

But TypeScript does not detect/infer types that matching my dictionary.

I have en.ts file:

const en = { blabla: 'blabla' }

With this configuration:

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';

import enּTranslation from './en';

i18n.use(initReactI18next).init({
    resources: {
        en: {
            translation: enּTranslation,
        },
    },
    lng: 'en',
    keySeparator: '.',
    interpolation: {
        escapeValue: false,
    },
});

export default i18n;

However, TypeScript does not using strong type for useTranslation hook.

I have also configured @types/react-i18n/index.d.ts file:

import 'react-i18next';

import type dictionary from '../../src/i18n/en';

declare module 'react-i18next' {
    interface CustomTypeOptions {
        resources: typeof dictionary;
    }
}

and configured tsconfig.json file:

{
    "extends": "../../tsconfig.base.json",
    "compilerOptions": {
        "target": "es5",
        "module": "esnext",
        "lib": ["dom", "dom.iterable", "esnext"],
        "baseUrl": "./",
        "jsx": "react-jsx",
        "paths": {
            "@/interfaces/*": ["src/interfaces/*"],
            "@/ui/*": ["src/components/ui/*"],
            "@/containers/*": ["src/components/containers/*"],
            "@/layout/*": ["src/components/layout/*"],
            "@/data/*": ["src/data/*"],
            "@/utils/*": ["src/utils/*"],
            "@/store/*": ["src/store/*"],
            "@/images/*": ["src/assets/images/*"],
            "@/assets/*": ["src/assets/*"],
            "@/hooks/*": ["src/hooks/*"],
            "@/models/*": ["src/models/*"],
            "@/styles/*": ["src/styles/*"]
        },
        "typeRoots": ["./@types", "./node_modules/@types"],
        "plugins": [{ "name": "typescript-plugin-css-modules" }]
    }
}

The packages I use are up to date

CodePudding user response:

Change declare module 'react-i18next' { to declare module 'i18next' {

https://www.i18next.com/overview/typescript

  • Related