You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为translationWrapper返回的customTFunc实现动态参数类型推导

实现动态类型的React翻译钩子包装器

我正在为React翻译钩子编写一个包装器,用于替换应用中的文本。现有如下translationWrapper函数,它会返回customTFunc:

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 };
};

使用示例:

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

我希望customTFunc的参数translationText的类型能根据传入translationWrapper的参数动态确定:当传入的translationName为"Notifications"时,参数类型应为Normalize<typeof Notifications>;传入"Configuration"时对应Normalize<typeof Configuration>。请问该如何实现?


解决方案

要实现这个动态类型匹配,你可以通过泛型结合映射类型来关联translationName和对应的翻译键类型:

1. 定义翻译类型映射

首先创建一个类型映射,把每个translationName对应到它的翻译对象类型:

// 假设你已经有这些翻译对象的定义
const FormValidations = { /* 你的表单验证翻译键 */ };
const Notifications = { /* 你的通知翻译键 */ };
const Configuration = { /* 你的配置项翻译键 */ };

// 创建类型映射,关联名称与对应翻译对象类型
type TranslationMap = {
  FormValidations: typeof FormValidations;
  Notifications: typeof Notifications;
  Configuration: typeof Configuration;
};

2. 改造translationWrapper为泛型函数

将translationWrapper改成泛型函数,让它的参数translationName对应到TranslationMap的键,通过泛型推导自动匹配对应的翻译键类型:

export const translationWrapper = <T extends keyof TranslationMap>(translationName: T) => {
    const { t } = useTranslation(translationName);

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

    return { customTFunc };
};

3. 效果验证

现在传入不同的translationName时,customTFunc的参数类型会自动匹配:

// customTFunc参数类型为Normalize<typeof FormValidations>
const { customTFunc: formT } = translationWrapper('FormValidations');
formT('form_validation_translation'); // 类型校验通过

// customTFunc参数类型为Normalize<typeof Notifications>
const { customTFunc: notifyT } = translationWrapper('Notifications');
notifyT('notification_expired'); // 类型校验通过

// customTFunc参数类型为Normalize<typeof Configuration>
const { customTFunc: configT } = translationWrapper('Configuration');
configT('config_theme_dark'); // 类型校验通过

关键说明

  • 泛型参数T被约束为keyof TranslationMap,确保只能传入合法的翻译名称,避免无效输入。
  • TranslationMap[T]会根据T的具体值动态获取对应的翻译对象类型,再通过Normalize处理后作为translationText的类型,实现了参数类型的动态绑定。
  • 这种方式既保留了TypeScript的类型安全特性,又满足了不同翻译模块的类型差异化需求。

内容的提问来源于stack exchange,提问作者Rishab Gupta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 23:50:44