Dynamically get the type for the function returned from a function

Viewed 38

So, I am writing a translation wrapper for the react translation hook to replace some text on the app. I have a translationWrapper function that returns a customTFunc as shown below:

export const translationWrapper = (translationName: 'FormValidations' | 'Notifications' | 'Configuration') => {
    const { t } = useTranslation(translationName);

    const customTFunc = (translationText: Normalize<typeof FormValidations>) => {
        const translatedText = t(translationText);
        if (someCondition) {
            return translatedText.replace("oldText", 'newText');
        }
        return translatedText;
    };

    return { customTFunc };
};

Usage:

const { customTFunc } = translationWrapper('FormValidations');
const translatedText = customTFunc('form_validation_translation')

For the customTFunc I want to have its argument translationText dynamically typed based on what was passed to the translationWrapper.

So, if the translationName is "Notifications"; I want the translationText to be Normalize<typeof Notifications>

1 Answers

You haven't made clear what do you mean by "dynamically typed based on..." but the general approach would be:

export const translationWrapper = <T extends 'FormValidations' | 'Notifications' | 'Configuration'>(translationName: T) => {
    const { t } = useTranslation(translationName);

    const customTFunc = (translationText: Normalize<typeof FormValidations>) => { // Here you can use type 'T', for example Normalize<T>
        const translatedText = t(translationText);
        if (someCondition) {
            return translatedText.replace("oldText", 'newText');
        }
        return translatedText;
    };

    return { customTFunc };
};

First you define a type parameter name T, which is extended from a union, then you can use T anywhere you want within the function.

Related