'Dynamically getting the keys from a nested object
I have a 3 level object will be generated similar to how openApi works, at project install time, or as a first step at compile time.
const translations = {
26: {
ro: {
test: 'test',
},
en: {
lorem: 'test',
test: 'test',
},
},
32: {
en: {
test: 'test',
},
},
};
The structure represents:
translations -> moduleID (dynamic) -> language (dynamic based on some other settings) -> dynamic based on moduleID
Later in my code we want:
const lang = 'en'
function getModuleTranslations<K extends keyof typeof x, T extends keyof typeof x[K][lang]>(mid: K): (key: T) => any {
return (key) => x[mid][lang][key];
}
....
const translate = getModuleTranslations(32); // We want type checking & autocomplete here
const testString = translate('test'); // We want type checking & autocomplete here as well based on the above getModuleTranslations(32)
In our case, the language param will be given by the class, at runtime.
I found multiple ways of accessing nested properties this way (translations, '32.en.test'), but this isn't what we want.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
