I have created a custom hook that should return the appropriate text options based on the specified region. However, I am unsure about the specific generic type required to access the available object keys in the output. Currently, the keys are not being recognized.
Here is the code for the hook with an incomplete generic:
interface Translate {
[keys: string]: {
ru: string
en: string
}
}
export function useTranslate<T extends Translate, R extends keyof T>(translate: T) {
const lang = Location.language
const response: { [keys: R]: string } = {}
Object.keys(translate).forEach(name => {
if (lang === 'ru-RU') {
response[name] = translate[name].ru
} else {
response[name] = translate[name].en
}
})
return response
}
Example usage of the hook:
const translate = useTranslate({
home: {
en: 'Home',
ru: 'Главная',
},
shop: {
en: 'Shop',
ru: 'Магазин',
},
suppliers: {
en: 'Suppliers',
ru: 'Поставщикам',
},
faq: {
en: 'FAQ',
ru: 'FAQ',
},
reviews: {
en: 'Reviews',
ru: 'Отзывы',
},
})
//return if EN region {
home: 'Home',
shop: 'Shop',
...
}
//return if RU region {
home: 'Главная',
shop: 'Магазин',
...
}
The hook will return either the English or Russian version, but not both.
TODO: Enable autocomplete to suggest which keys can be referenced.
Thank you in advance for your help!