我想简单地使用自定义属性从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"
}
答案 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
}
}
}
属性添加到所有请求实例:
: