Express-Typescript中Apollo Server expressMiddleware类型不兼容错误
Express-TypeScript 中 ApolloServer expressMiddleware 类型错误解决
搭建Express-Typescript的GraphQL服务器时,使用expressMiddleware配置GraphQL端点遇到类型错误,具体错误信息如下:
类型为'RequestHandler<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'的参数无法赋值给类型为'Application<Record<string, any>>'的参数。
问题代码
import "dotenv/config"; import express from 'express'; import cors from 'cors'; import { expressMiddleware } from '@apollo/server/express4'; import { ApolloServer } from '@apollo/server'; const gqlServer = new ApolloServer({ typeDefs: ` type Query { hello: String } `, resolvers: { Query: { hello: () => 'Hello world!', } }, }); async function init() { const app = express(); const port = Number(process.env.PORT) || 4000; app.use(cors()); app.use(express.json()); app.use(express.urlencoded({ extended: true })); await gqlServer.start(); app.get('/', (req, res) => { res.send('Hello World!'); }); app.use("/graphql", expressMiddleware(gqlServer)); // 错误位置 app.listen(port, () => { console.log(`Server is running on http://localhost:${port}`); }); } init();
tsconfig.json 配置
{ "compilerOptions": { "target": "es2016", "module": "CommonJS", "rootDir": "./src", "outDir": "./dist", "esModuleInterop": true, "forceConsistentCasingInFileNames": true, "strict": true, "skipLibCheck": true } }
package.json 配置
{ "name": "server", "version": "1.0.0", "main": "index.js", "type": "module", "scripts": { "build": "tsc", "start": "node dist/index.js", "dev": "tsc-watch --onSuccess \"npm start\"", "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "description": "", "dependencies": { "@apollo/server": "^4.11.2", "cors": "^2.8.5", "dotenv": "^16.4.7", "express": "^4.21.2", "graphql": "^16.10.0" }, "devDependencies": { "@types/cors": "^2.8.17", "@types/dotenv": "^8.2.3", "@types/express": "^5.0.0", "nodemon": "^3.1.9", "tsc": "^2.0.4", "tsc-watch": "^6.2.1", "typescript": "^5.7.2" } }
错误原因及解决方案
错误根源在于@types/express版本不匹配:安装的是v5.0.0类型包,但实际使用的express是v4.x版本,两者类型定义存在差异,导致expressMiddleware返回的请求处理器类型无法被express v4的app.use正确识别。
解决步骤:
- 卸载当前的
@types/express:
npm uninstall @types/express
- 安装适配express v4的类型包:
npm install -D @types/express@4
- 重新编译项目,类型错误即可消除。
额外优化:package.json中设置了"type": "module",但tsconfig里"module"配置为CommonJS,模块系统不匹配可能引发其他问题,建议将tsconfig的module改为ESNext或ES2020,保持与package.json一致。
内容的提问来源于stack exchange,提问作者Lovish Bansal
相关产品推荐
相关产品推荐

