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

使用i18next时为何出现插值参数count仅支持number类型的TS错误?

i18next TypeScript类型错误:count参数仅允许number类型的原因

问题场景

你的翻译JSON文件内容:

{
  "text": "New count is {{count}}"
}

在index.ts中执行代码:

const translatedText = i18n.t("text", { count: "test" }); // 触发TypeScript错误:count仅允许number类型
const translatedText2 = i18n.t("text", { count: 1 }); // 正常执行

原因分析

这是因为项目中i18next的TypeScript类型系统自动将count插值变量推断为了number类型,常见触发场景包括:

  • 使用了i18next类型生成工具(如i18next-scanner或Vite生态的翻译类型推导插件),这类工具扫描翻译模板时,默认会将含"count"这类数字相关命名的插值变量推断为number类型。
  • 项目中手动扩展了i18next的类型定义,将text键的count参数限定为number类型。
  • 依赖的@types/i18next配合项目TS严格配置,开启了插值变量的上下文类型推断,自动将未明确标注的变量归为number。

解决办法

1. 手动声明多类型兼容的翻译键类型

扩展i18next的类型定义,明确count允许string或number类型:

// src/i18n.d.ts
declare module 'i18next' {
  interface CustomTypeOptions {
    defaultNS: 'translation';
    resources: {
      translation: {
        text: { count: string | number };
      };
    };
  }
}

export {};

2. 修改类型生成工具配置

如果使用自动类型生成工具,在配置文件中指定count的类型为string|number,覆盖默认的类型推断规则。

3. 临时放宽类型检查(不推荐)

若不需要严格的插值类型校验,可以为i18n调用添加类型断言:

const translatedText = i18n.t("text", { count: "test" } as any);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 10:50:58