javascript - 'NextHandleFunction' 类型的参数不可分配给 'PathParams' 类型的参数

标签 javascript node.js typescript express

我已经使用基本的 Express 服务器启动并运行了 TypeScript,但我遇到了一个问题。

import bodyParser from 'body-parser';
import express, { Express } from 'express';

const app: Express = express();
app.use(bodyParser.json()); // Error 1
app.use(bodyParser.urlencoded({ extended: true })); // Error 2

错误 1 ​​是这样的:

Property 'pop' is missing in type 'NextHandleFunction'. [2345]



所以bodyParser.json()正在返回 createServer.NextHandleFunction但没有 pop属性(property)。 NextHandleFunction@types/connect 中是这样定义的:
export type NextHandleFunction = (req: http.IncomingMessage, res: http.ServerResponse, next: NextFunction) => void;

是的,没有pop .但是我有什么办法来解决这个问题?

错误 2 是这样的:

Type 'NextHandleFunction' is not assignable to type '(string | RegExp)[]'. [2345]



在这里,bodyParser.urlencoded()还返回一个 createServer.NextHandleFunction ,但那不是类型 app.use()在寻找。

同样,不确定我在这里的选择。

包.json
"dependencies": {
    "@types/body-parser": "^1.17.0",
    "@types/connect": "^3.4.32",
    "@types/express": "^4.16.0",
    "@types/express-serve-static-core": "^4.16.0",
    "body-parser": "^1.18.3",
    "express": "^4.15.2",
    "express-serve-static-core": "^0.1.1"
},
"devDependencies": {
    "typescript": "^3.1.6"
}

最佳答案

我能够通过这种方式修复错误:

import bodyParser from 'body-parser';
import express, { Express, RequestHandler } from 'express';

const app: Express = express();
app.use(bodyParser.json() as RequestHandler);
app.use(bodyParser.urlencoded({ extended: true }) as RequestHandler);

关于javascript - 'NextHandleFunction' 类型的参数不可分配给 'PathParams' 类型的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53617019/

相关文章:

node.js - 在 node.js 中获取图像的宽度和高度

node.js - nodejs/express : does calling next() automatically return the function it is called from?

javascript - webpack css 加载器不工作

javascript - 如何进一步重构 ctx.fillStyle 的列和行?

node.js - 在项目中包含自定义 Yeoman 生成器

javascript - StencilJS 导出自定义类

javascript - 如何为 joi-objectid 提供接口(interface)?

javascript - Chai .js : Object contains/includes

javascript - 如何构建一个 npm 包以便它能够被导入/需要

mongodb - mongoose 模型不可调用 tslint 错误