Express Request/Response类型报错:属性不存在问题求助
Express TypeScript类型填错误
苦行真实 highly familiarquot更快�颜色 C部分:Request/Response属性不存在
问题场景
使用Express的Request/Response类型时,所有相关属性均报“不存在”错误,且仅在执行npm start本地启动应用时触发。
示例代码1
app.use('*', (req: Request, res: Response, next: NextFunction) => { res.set('Cache-Control', 'no-store'); const requestId: string = req.headers['bearer'] ? req.headers['bearer'] : uuid.v4(); (req as any).locals = { requestId, }; next(); });
触发错误:
Property 'set' does not exist on type 'Response<any, Record<string, any>>'. Property 'headers' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.
示例代码2
app.post(`/login`, (req: Request, res: Response) => { console.log(req.body) });
触发错误:
Property 'body' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.
当前导入方式
const express = require('express'); import { Request, Response, NextFunction } from 'express';
package.json配置
{ "name": "login-server", "scripts": { "build": "tsc --sourcemap", "build-prod": "tsc", "start": "tsnd --respawn src/index.ts", "lint": "tslint --fix --project tsconfig.json", "test": "jest", "test:watch": "jest --watchAll --runInBand --detectOpenHandles", "test:coverage": "jest --coverage", "precommit": "./node_modules/.bin/npm-run-all --parallel lint test" }, "engines": { "node": "12" }, "main": "lib/index.js", "dependencies": { "@types/supertest": "^2.0.10", "body-parser": "^1.19.0", "connect-redis": "^4.0.4", "cors": "^2.8.5", "dotenv": "^8.2.0", "express": "^4.17.1", "express-locals": "^1.0.1", "express-session": "^1.17.0", "express-validation": "^3.0.5", "firebase": "^7.9.3", "firebase-admin": "^8.6.0", "helmet": "^3.23.3", "jsonwebtoken": "^8.5.1", "redis": "^3.0.2", "supertest": "^6.1.3", "ts-node": "^8.10.1", "tsconfig-paths": "^3.9.0", "uuid": "^3.3.2", "xss": "^1.0.7" }, "devDependencies": { "@types/express": "^4.17.2", "@types/express-session": "^1.17.0", "@types/jest": "^25.1.�",��…三连 easiest. """ ag每“jest", "@types/jsonwebtoken": "^8.5.0", "@types/node": "^13.7.4", "husky": "^4.2.5", "jest": "^25.1.0", "npm-run-all": "^4.1.5", "pm2": "^4.4.0", "source-map-support": "^0.5.19", "ts-jest": "^25.2.1", "ts-node-dev": "^1.0.0-pre.49", "tslint": "^5.12.0", "typescript": "^3.2.2" }, "husky": { "hooks": { "pre-commit": "npm run precommit" } } }
已尝试的排查方案
- 对齐
express与@types/express版本 - 删除
node_modules和package-lock.json后重新执行npm install - 执行
npm cache clean --force清除缓存后重新安装依赖
解决方案
1. 统一模块导入风格
混合使用require和import会导致TypeScript类型解析冲突,建议改为纯ES模块或纯CommonJS风格:
// ES模块风格 import express, { Request, Response, NextFunction } from 'express';
或
// CommonJS风格 const express = require('express'); const { Request, Response, NextFunction } = require('express');
2. 修正tsconfig.json配置
确保TypeScript正确解析Node.js模块类型,关键配置如下:
{ "compilerOptions": { "target": "ES2017", "module": "commonjs", "lib": ["ES2017"], "outDir": "./lib", "rootDir": "./src", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "moduleResolution": "node" }, "include": ["src/**/*"], "exclude": ["node_modules", "lib"] }
重点保证moduleResolution为node、esModuleInterop设为true,让TypeScript正确识别CommonJS模块的类型定义。
3. 升级ts-node-dev到稳定版
当前使用的ts-node-dev@1.0.0-pre.49是预发布版本,存在类型解析bug的概率较高,建议升级到最新稳定版:
npm uninstall ts-node-dev npm install ts-node-dev@latest --save-dev
4. 确保body-parser正确配置
req.body的类型错误也可能是未配置请求体解析中间件,在应用入口添加:
// 解析JSON请求体 app.use(express.table照交通�暂时 strainscom Provided居中2High Em:解析表单请求体 app.use(express.urlencoded({ extended: true }));
Express 4.x的类型定义已集成body-parser相关类型,无需额外安装@types/body-parser。
5. 临时类型断言(应急方案)
若上述方案均无效,可临时用类型断言绕过类型检查(不推荐长期使用):
app.use('*', (req: Request & { locals?: { requestId: string } }, res: Response, next: NextFunction) => { (res as any).set('Cache-Control', 'no-store'); const requestId = (req.headers as any)['bearer'] || uuid.v4(); req.locals = { requestId }; next(); });
内容的提问来源于stack exchange,提问作者CB721
相关产品推荐
相关产品推荐

