reactjstypescripti18nextreact-i18next

How to extract translation keys from the parameter of 't' function in react-i18next to the separate type?


How can I extract the type of the possible keys from t function? It works perfectly when I use it inside components after useTranslation() call, so I want to use the type anywhere, for example, as the type of a prop.

To Reproduce

I tried something like this, but it looks weird and I get the error TS2589: Type instantiation is excessively deep and possibly infinite

 type TranslationKeys = Parameters<ReturnType<typeof useTranslation>['t']>[0]

My declaration file:

import en from 'assets/i18n/en-US.json';

type Resources = typeof en;

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

en-US.json file:

{
  "posts": {
    "headerTitle": "Posts",
    "id": "Id",
    "deviceId": "Device Id",
    ...
  },
  "users": {
    "headerTitle": "Users",
     ....
  },
}

I want to have a type of these values: 'posts:headerTitle' | 'post:id' | 'post:deviceId' | 'users:headerTitle' and so on. And useTranslation function can infer the possible keys internally to use them in t function call, I want to use them too

I can construct it on myself by Resources manipulations, but it should be possible to do it "natively"

Your Environment


Solution

  • I have only tested with i18next 22.x.x version:

    import { Namespace, TFuncKey } from 'i18next';
    TFuncKey<Namespace>
    

    i18next 23.x.x:

    TFunction<Namespace>