重写Typescript中Response.end的正确方法? [英] Correct way to override Response.end in Typescript?

查看:159
本文介绍了重写Typescript中Response.end的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Typescript写一个Express-Session的替代品(因为我想使用JWT令牌而不是cookie).

I'm writing a replacement for express-session in Typescript (because I want to use JWT tokens rather than cookies).

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

I've hit a snag when it comes to overriding Response.end (in order to save the session after the request has been handled).

签名似乎如下:

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替代品.

However, I am unsure how to provide a replacement for res.end which matches these call signatures.

express-session似乎像这样被覆盖:

express-session appears to override like this:

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

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

However, when I try to provide a replacement:

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'.

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

The first definition does work fine, however:

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

}

任何建议将不胜感激!

更新:我发现我可以通过将Response对象转换为 any :

Update: I've found that I can work around this issue by casting the Response object to any:

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

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

However, my original question still stands: is there a way to do this in a typed way?

推荐答案

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

The second argument can be an encoding (string) or a callback (Function). Your provided method does not consider that scenario. Also, there is no guarantee the first argument will be there. You need to do:

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

}

这篇关于重写Typescript中Response.end的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆