typescript - Åsidosätt i18next TFunction med en enum från en annan fil
Jag försöker åsidosätta TFunction i i18next-paketet.
Det jag försöker uppnå är att säkerställa typning av de använda i18n-nycklarna som:
t('invalid-key') // is invalid
t('key1') // is valid
Så jag gjorde följande i18next.d.ts-fil för att åsidosätta typen av TFunction:
type Keys = 'key1' | 'key2'
declare module 'i18next' {
export type TFunction = (key: Keys) => string
}
Det fungerar men så snart jag försöker importera den typen från en annan fil går TFunction-typen tillbaka till den ursprungliga.
Har någon ett tips för att hjälpa mig importera nycklarna i deklarationsfilen?
Konstigt nog fungerar importen när jag gör det genom useTranslation-hooken från react-i18next-paketet:
import { I18nKey } from '../modules/core/i18n/i18nKey'
declare module 'react-i18next' {
export function useTranslation(): {
t: (key: I18nKey) => string
}
}
Svar #1
Om du exporterar Keys i deklarationsfilen kommer deklarationsfilen att bli en modul. Detta gör att TypeScript inte inkluderar filen globalt. Skapa en separat fil för declare module för att inkludera den globalt.
Om du vill importera i en global fil som deklarerar ett modul bör du importera dem inuti modulen på detta sätt.
declare module 'react-i18next' {
import { I18nKey } from '../modules/core/i18n/i18nKey'
export function useTranslation(): {
t: (key: I18nKey) => string
}
}
