Here is a slightly different approach that I suggest: Instead of translating directly, store the keys in an enum in a translation.json file like this:
export enum Test {
test1 = 'dropdown.doSomething.test1',
test2 = 'dropdown.doSomething.test2',
}
In this way, the enum will not be dependent on the current language, allowing for easy translation of values from the enum using the following method:
const enTranslations = {
dropdown: {
doSomething: {
test1: "1 - do something"
}
}
};
const getTranslatedText = (translations, keys: string[]) => keys.reduce((acc, curr) => acc[curr], translations);
const key1 = Test.test1
const translatedEnText = getTranslatedText(enTranslations, key1.split('.'));
You can then display the translatedEnText
, or pass it into a function call where
translatedEnText === '1 - do something'
.
If you need the same key's text in different languages, simply use the getTranslatedText
function with another translation object such as deTranslations
.
To map your enum into an object with the same keys and translated values, you can follow this example:
const testEng = Object.values(Test).reduce((acc, key) => ({ ...acc, [key]: getTranslatedText(enTranslations, key.split('.'))}), {})
The reduce function will start with an empty object {}
as acc
, adding the translated text from
getTranslatedText(enTranslations, key.split('.'))
as the value under the
key
key on each iteration.
Playground