物业'推动'类型'中缺少(请求:NtlmRequest,响应:响应)=>空隙'

时间:2018-03-15 15:28:13

标签: node.js typescript express typescript-typings

我想简单地使用自定义属性从Express框架扩展Request对象:

import express = require('express')

export interface NtlmRequest extends express.Request {
     ntlm: NtlmInfo
}

而是用作express.Request的参数类型。

let app = express();
app.all('*', (request:NtlmRequest, response:Response) => {
    console.log(request.ntlm.UserName)
});

app.listen(1243)

NtlmInfo是另一个简单包含字符串属性的接口:

export interface NtlmInfo { UserName: string  [...] }

但是这给了我一个错误,即请求Type不兼容:

error TS2345: Argument of type '(request: NtlmRequest, response: Response) => void' is not assignable to parameter of type 'RequestHandlerParams'.
  Type '(request: NtlmRequest, response: Response) => void' is not assignable to type '(RequestHandler | ErrorRequestHandler)[]'.
    Property 'push' is missing in type '(request: NtlmRequest, response: Response) => void'.

无法理解这一点,因为我从原始的express.Request对象继承并查看了没有任何push属性的打字定义。

安装了以下软件包:

"dependencies": {
    "express": "^4.16.2",
    "express-ntlm": "^2.2.4"
  },
  "devDependencies": {
    "@types/express": "^4.11.1",
    "@types/node": "^9.4.7",
    "typescript": "^2.7.2"
  }

1 个答案:

答案 0 :(得分:3)

您的代码存在两个问题。第一个很容易修复,对于response我相信您使用lib.d.ts Response版本的express.Response。您应该使用NtlmRequest

第二个更微妙。要使用ntlm作为请求类型,您需要使all成为可选项。编译器,期望express.Request将采用具有第一个参数express.Request的函数,因此您传递的函数不能要求第一个参数具有比export interface NtlmRequest extends express.Request { ntlm?: NtlmInfo } //Will work app.all('*', (request:NtlmRequest, response:express.Response) => { console.log(request.ntlm.UserName) }); <更多的属性< / p>

Request

另一种选择是扩展全球快递ntlm。这会将import * as express from 'express' interface NtlmInfo { UserName: string} declare global { namespace Express { export interface Request { ntlm: NtlmInfo } } } 属性添加到所有请求实例:

: