【问题标题】:Correct way to override Response.end in Typescript?在 Typescript 中覆盖 Response.end 的正确方法?
【发布时间】:2023-04-10 17:23:01
【问题描述】:

我正在 Typescript 中编写 express-session 的替代品(因为我想使用 JWT 令牌而不是 cookie)。

在覆盖 Response.end 时遇到了麻烦(为了在处理请求后保存会话)。

签名看起来如下:

end(cb?: Function): void;
end(chunk: any, cb?: Function): void;
end(chunk: any, encoding?: string, cb?: Function): void;

所以下面的工作:

const end: {
                (cb?: Function): void;
                (chunk: any, cb?: Function): void;
                (chunk: any, encoding?: string, cb?: Function): void; 
            } = res.end;

但是,我不确定如何为 res.end 提供与这些调用签名匹配的替代品。

express-session 似乎像这样覆盖:

res.end = function end(chunk, encoding) {

但是,当我尝试提供替代品时:

res.end = function(chunk: any, encoding?: string, cb?: Function)
{

}

编译器呻吟:

error TS2322: Type '(chunk: any, encoding?: string | undefined, cb?: Function | undefined) => void' is not assignable to type '{ (cb?: Function | undefined): void; (chunk: any, cb?: Function | undefined): void; (chunk: any, ...'.
  Types of parameters 'encoding' and 'cb' are incompatible.
    Type 'Function | undefined' is not assignable to type 'string | undefined'.
      Type 'Function' is not assignable to type 'string | undefined'.
        Type 'Function' is not assignable to type 'string'.

第一个定义确实可以正常工作,但是:

res.end = function(cb?: Function): void
{

}

任何建议将不胜感激!

更新:我发现我可以通过将 Response 对象转换为 any 来解决此问题:

(<any>res).end = function(chunk: any, encoding?: string): void
{
    end.call(res, chunk, encoding);
};

但是,我最初的问题仍然存在:有没有办法以打字的方式做到这一点?

【问题讨论】:

  • 我很惊讶你提供的签名是有效的,不应该是:(cb?: Function): void; | (chunk: any, cb?: Function): void; | (chunk: any, encoding?: string, cb?: Function): void;
  • 好吧,实际上我只是直接从 Typescript 编译器的错误输出中复制了我正在使用的语法。它有效,我想这只是表示同一事物的另一种方式。

标签: typescript express


【解决方案1】:

第二个参数可以是编码(字符串)或回调(函数)。您提供的方法不考虑这种情况。此外,不能保证第一个参数会在那里。你需要做的:

res.end = function(chunk?: any, encodingOrCb?: string | Function, cb?: Function): void {

}

【讨论】:

    猜你喜欢
    • 2016-10-19
    • 2017-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-16
    • 2019-11-03
    • 2012-05-17
    相关资源
    最近更新 更多