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
相关产品推荐
相关产品推荐

