Node.js 财产';推动';类型'中缺少;(请求:NtlmRequest,响应:response)=>;无效';

Node.js 财产';推动';类型'中缺少;(请求:NtlmRequest,响应:response)=>;无效';,node.js,typescript,express,typescript-typings,Node.js,Typescript,Express,Typescript Typings,我只想使用自定义属性扩展Express framework中的请求对象: import express = require('express') export interface NtlmRequest extends express.Request { ntlm: NtlmInfo } 它用作express.Request的参数类型 let app = express(); app.all('*', (request:NtlmRequest, response:Response)

我只想使用自定义属性扩展Express framework中的
请求
对象:

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  [...] }
但这给了我一个错误,即请求类型不兼容:

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"
  }

您的代码有两个问题。第一个问题很容易解决,因为
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)
});
另一个选项是扩展global express
请求
。这将把
ntlm
属性添加到all请求实例:

import * as express from 'express'
interface NtlmInfo { UserName: string}
declare global {
    namespace Express {
        export interface Request {
            ntlm: NtlmInfo
        }
    }
}

Response
的版本是正确的,因为我已经在示例代码中使用了类似的
express.Response
。但是第二个问题是我的问题:将
ntlm
属性更改为optional解决了这个问题。谢谢!:)