【问题标题】:Property 'push' is missing in type '(request: NtlmRequest, response: Response) => void'类型“(请求:NtlmRequest,响应:响应)=> void”中缺少属性“push”
【发布时间】:2018-08-24 11:53:40
【问题描述】:

我想使用自定义属性从 Express 框架中简单地扩展 Requestobject:

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 属性的 Typing 定义。

安装了以下软件包:

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

【问题讨论】:

    标签: node.js typescript express typescript-typings


    【解决方案1】:

    您的代码有两个问题。第一个很容易修复,对于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)
    });
    

    另一种选择是扩展全局快递Request。这会将 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 解决了问题。谢谢! :)
    猜你喜欢
    • 1970-01-01
    • 2017-11-29
    • 2016-06-05
    • 1970-01-01
    • 2020-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-30
    相关资源
    最近更新 更多