Override i18next TFunction using an enum from an other file

Viewed 806

I'm trying to override the TFunction of the i18next package.

What I'm trying to achieve is ensuring typing of the used i18n keys as:

t('invalid-key') // is invalid
t('key1') // is valid

So I made the following i18next.d.ts file to override the type of the TFunction:

type Keys = 'key1' | 'key2'

declare module 'i18next' {
    export type TFunction = (key: Keys) => string
}

It works but as soon as I try import that type from an other file the TFunction type goes back to the original one.

Does someone have a hint to help me import the keys in the declaration file?


Oddly import works when I do it through the useTranslation hook of the react-i18next package:

import { I18nKey } from '../modules/core/i18n/i18nKey'

declare module 'react-i18next' {
    export function useTranslation(): {
        t: (key: I18nKey) => string
    }
}
1 Answers

If you export Keys in the declaration file, the declaration file will become a module. This causes TypeScript to not include the file globally. Make a separate file for the declare module to include globally.


If you want to import in a global file that declares a module you should import them inside the module like this.

declare module 'react-i18next' {
    import { I18nKey } from '../modules/core/i18n/i18nKey'

    export function useTranslation(): {
        t: (key: I18nKey) => string
    }
}
Related