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

TypeScript中Express集成i18next报错:Request无t属性

解决Express + TypeScript中i18next req.t 类型错误

这个问题是因为TypeScript默认的Request接口并没有包含i18next中间件添加的t方法,需要通过扩展Express类型来解决,具体步骤如下:

1. 创建类型声明文件

在项目的src目录下新建types/express.d.ts文件(路径可调整,只要TypeScript能扫描到),内容如下:

import { Request } from 'express';
import { TFunction } from 'i18next';

declare module 'express' {
  interface Request {
    t: TFunction;
  }
}

如果你的i18next配置了命名空间或自定义资源类型,可以更精确地指定TFunction的泛型参数,比如:

// 假设你的命名空间是'translation'
TFunction<'translation', undefined>

2. 配置TypeScript识别类型文件

确保tsconfig.json的include和typeRoots配置包含你新建的类型文件:

{
  "compilerOptions": {
    // 其他编译选项...
    "typeRoots": ["./node_modules/@types", "./src/types"]
  },
  "include": [
    "src/**/*",
    "src/types/**/*"
  ]
}

3. 优化导入方式(可选)

你的代码中用了require导入中间件,TypeScript项目建议改用import:

// index.ts
import i18nextMiddleware from 'i18next-express-middleware';
import i18next from './services/i18next';

app.use(i18nextMiddleware.handle(i18next));
app.use('/users', usersRoute);

完成以上步骤后,TypeScript就会识别req.t方法,不再抛出类型错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 19:45:21