I'm struggling to use a generic key in the return type for a function
With the following object as the "data model" here
const TRANSLATIONS = {
application_card: { a: string; b: string}
home: { c: string}
}
I have defined the following function which will take in a key TNamespace from TRANSLATIONS, and return typeof TRANSLATIONS[TNamespace]
function useI18Namespace<TNamespace extends keyof typeof TRANSLATIONS>(
namespace: TNamespace
): typeof TRANSLATIONS[TNamespace] {
const { t } = useTranslation(namespace as string);
switch (namespace) {
case 'application_card': {
return {
a: t('a', TRANSLATIONS.application_card.a),
b: t('b', TRANSLATIONS.application_card.b)
}
}
case 'home': {
return {
c: t('c', TRANSLATION.home.c)
};
}
}
}
However this doesn't "narrow" the type correctly,
I get an error telling me that c is missing from my return value (when returning application_card
And that a and b are missing when returning home
But when I hardcode the return type:
typeof TRANSLATIONS['application_card']
It narrows correctly, and I don't get any errors (in the return for application_card)
It seems that typeof TRANSLATIONS[TNamespace] is just the same as typeof TRANSLATIONS which I don't understand.
Is this a bug in TS? Or am I doing something wrong?