So my backend has a JSON like this
name: "Hello",
nameTranslations: {nl:"Hallo", en: "Hello", fr: "Bonjour"}
description: "Hello",
descriptionTranslations: {nl:"Hallo", en: "Hello", fr: "Bonjour"}
I want to build a function where I'll put in the object and key and it will automatically find the best translation possible. It's easy in Javascript but I want to get Typescript right so I won't be dealing with runtime bugs if I forgot to query the translations (I use GraphQL)
function getText(object, key, language) {
const best = object[`${key}Translations`][language];
if (best) {
return best;
}
return object[key];
}
Some Typescript requirements I have
- I want only the keys possible of the input object
- I want Typescript to return an error if the key is not available on the object or the 'keyTranslations'
Update
Based on the answer of @michmich112 I did go with the following function
function translate<T extends BackendTranslations>(translations: T, fallback: string, language: keyof BackendTranslations) => {
return translations[language] || fallback;
}
translate(project.nameTranslations, project.name)
I will keep the answer open, since I'm still interested if this could work in Typescript
Here is my try:
Please keep in mind, my solutions works only with TypeScript 4.*