Skip to main content

Autocomplete configuration

Autocompletion for translation keys is available in Typescript projects. Because json must be parsed at compile time, you will need to create your own useAutocompleteT hook with Talkr's Autocomplete type wrapper.

Here's how to do it:

  • Make sure you use Typescript >=4.5.5 (we don't guarantee it will work on older versions)
  • Create a translate.tsx file anywhere in your app(translate.tsx can be named as you want)
  • Import your main language JSON translation (ex: en.json)
  • Instantiate autocompletion with Talkr's Autocomplete
  • Export a useAutocompleteT hook around Talkr's useT()
import { useT, Autocomplete, TParams, tr } from "talkr";
import en from "./en.json";

type Key = Autocomplete<typeof en>;

export const useAutocompleteT = () => {
const { locale, setLocale, languages, defaultLanguage } = useT();
return {
setLocale,
locale,
T: (key: Key, params?: TParams) =>
tr({ locale, languages, defaultLanguage }, key, params),
};
};

If you prefer to keep the useT naming, just write:

import { useT as useTr, Autocomplete, TParams, tr } from "talkr";
import en from "./en.json";

type Key = Autocomplete<typeof en>;

export const useT = () => {
const { locale, languages, defaultLanguage } = useTr();
return {
T: (key: Key, params?: TParams) =>
tr({ locale, languages, defaultLanguage }, key, params),
};
};