Reputation: 1063
I use i18next and I want to pass the t function prop to my interface.
exp:
const { t } = useTranslation();
export interface ITranslate {
translate: ... type?
}
what is the type of the " t " variable ?
Upvotes: 7
Views: 10097
Reputation: 11
Neither of the answers worked for me using the current latest version of i18n (23.10.1) on a react + TS project.
Adding type
resolved the import issue.
import type { TFunction } from "i18next";
Upvotes: 0
Reputation: 94
The best way is just to use
t: typeof i18next.t
In this scenario if you also used <const>
operator for translation files it will guard input in the translation function, while TFunction
will not.
Example of <const>
usage for translations:
# translations.ts file
import en from "./en.json"
import fr from "./fr.json"
import cz from "./cz.json"
export default <const>{
en,
fr,
cz
}
# i18next.d.ts file
import translations from "./translations"
declare module "i18next" {
interface CustomTypeOptions {
defaltNS: 'en',
resources: typeof translations["en"]
}
}
In this way you will have following results in imagined app:
# en.json file
{
"first": "This is first",
"second": "This is second"
}
# Component.tsx file
import i18next from "18next";
const shouldWork = i18next.t('first')
const shouldFail = i18next.t('third') // TS will show an error
Be sure to have "resolveJsonModule": true
in tsconfig.json
file
Upvotes: 6
Reputation: 118
maybe this will work:
import { TFunction } from "react-i18next";
export interface ITranslate {
translate: TFunction
}
Upvotes: 5
Reputation: 43206
You can use ReturnType
utility type:
export interface ITranslate {
translate: ReturnType<typeof useTranslation>['t']
}
Upvotes: 2