使用react-i18next传递动态键时出现"No overload matches this call"错误
解决react-i18next动态传键的TypeScript类型错误
错误信息
No overload matches this call. Overload 1 of 12, '(key: TemplateStringsArray | "translation:myapp" | "translation:login" | "translation:forgot_password" | "translation:common" | "translation:validation" | ... 98 more ... | (TemplateStringsArray | ... 102 more ... | "translation:messages.success")[]): string | ... 16 more ... | { ...; }', gave the following error. Argument of type 'string' is not assignable to parameter of type 'TemplateStringsArray | "translation:myapp" | "translation:login" | "translation:forgot_password" | "translation:common" | "translation:validation" | ... 98 more ... | (TemplateStringsArray | ... 102 more ... | "translation:messages.success")[]'. Overload 2 of 12, '(key: Normalize<{ myapp: string; login: { title: string; welcome: string; description: string; username: string; password: string; "forgot-password": string; "create-account": string; google: string; facebook: string; github: string; }; ... 5 more ...; messages: { ...; }; }> | Normalize<...>[]): string | ... 16 more ... | { ...; }', gave the following error. Argument of type 'string' is not assignable to parameter of type 'Normalize<{ myapp: string; login: { title: string; welcome: string; description: string; username: string; password: string; "forgot-password": string; "create-account": string; google: string; facebook: string; github: string; }; ... 5 more ...; messages: { ...; }; }> | Normalize<...>[]'.
出错代码片段
<Grid item xs={12} md={4} key={item.key}> <TextField fullWidth id={item.key} label={t(item.key)} /* 错误位置 */ type="text" variant="outlined" name={item.key} defaultValue={params[item.key]} /> </Grid>
参考配置文件
import i18next from 'i18next'; import { initReactI18next } from 'react-i18next'; import translation from './en/translation.json'; export const resources = { en: { translation } }; i18next.use(initReactI18next).init({ debug: false, resources, defaultNS: 'translation', interpolation: { escapeValue: false }, react: { useSuspense: true }, compatibilityJSON: 'v3', returnNull: true, fallbackLng: 'en' }); export default i18next;
解决方法
1. 类型断言(快速修复)
直接将动态键断言为翻译文件的键类型,让TypeScript认可该键的合法性:
label={t(item.key as keyof typeof translation)}
2. 定义严格类型(推荐)
在配置文件或单独类型文件中导出翻译键的类型,再给item的key字段指定该类型,从根源约束键的合法性:
// 在i18n配置文件中添加 export type TranslationKeys = keyof typeof translation; // 定义表单项的类型 type FormItem = { key: TranslationKeys; // 其他字段按需定义 }; // 使用时约束items的类型 const items: FormItem[] = [...];
此方法既解决类型错误,又保留TypeScript的类型校验能力,避免传入无效翻译键。
3. 临时绕过类型检查(不推荐)
若暂时无需类型校验,可通过any断言跳过检查,但会丢失类型提示和安全保障:
label={t(item.key as any)}
原因说明
react-i18next会根据翻译文件自动生成严格的类型约束,确保传入t函数的键是翻译文件中存在的有效键。而动态字符串string类型过于宽泛,不符合生成的类型要求,因此触发类型不匹配错误。
内容的提问来源于stack exchange,提问作者Ghaem
相关产品推荐
相关产品推荐

